Video autoplay functionality activated by resizing the screen

Greetings everyone, I am excited to share my first post here. After some thorough research, I stumbled upon a piece of code for an external .js file that is almost flawless in its ability to load an image instead of a video if the screen size is less than or equal to 1024:

$(document).ready(function() {

$(window).resize(function(){
            var width = $("body").width();
            if(width <= 1024){
                $("#media_div").html("<img src='/img/benhat1280.jpg' />");
            }else{
                $("#media_div").html('<video src="/img/CT_HQ.mp4" autoplay mute loop />');
                $("#media_div img").css("height","auto");
                $("#media_div").fadeIn(2000);
            }
        })
      });

However, when the screen size is greater than 1024, the video will only load after resizing the browser window. Additionally, the .fadein function seems to be malfunctioning.

Warm regards, Benjamin

Answer №1

To ensure your resizing code functions smoothly, place it inside a function and invoke it during both resize events and at initialization. Additionally, set the opacity to 0 before fading in.

$(document).ready(function() {

        function handleResize(){
            var width = $("body").width();
            if(width <= 1024){
                $("#media_div").html("<img src='/img/benhat1280.jpg' />");
            }else{          
                $("#media_div").html('<video src="/img/CT_HQ.mp4" autoplay mute loop />');
                $("#media_div img").css("height","auto");
                $("#media_div").css('opacity', 0);
                $("#media_div").fadeIn(2000);
            }
        }

        $(window).resize(function(){
             handleResize();
        };

        handleResize();
     });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Promises for click event handling

Currently, I'm experimenting with using promises to improve the readability and functionality of my code when dealing with AJAX methods. My current experiment involves a function called getBookIds that sends an AJAX request to a database to retrieve t ...

substitute tags

Is there a way to change the tagName of a tag using jQuery? For example, if I have an HTML document and I want to replace all 'fieldset' with 'div'. Any suggestions would be appreciated! ...

Using jQuery to Retrieve Items from an Object Contained in .val()

If I use the .val() method and get a string representation like this: { "dept_catg_grp_nbr":"239", "dept_catg_grp_desc":"TABLE TOP GROUP" } What is the best way to access each of the individual elements? ...

Display HTML content in a modal dialog box without parsing it

I'm currently working on a website showcasing various HTML and CSS spinners and loaders. Each example opens a modal window upon click, where I aim to display the corresponding code for that spinner so users can easily copy and implement it in their ow ...

How to maintain the original size of an image when setting it as a background with CSS

My challenge is using a large image as a background, as it always resizes automatically and cannot display the full height of the image. How should I handle this issue? One approach is to set the height to match the image's height. However, this mean ...

bootstrap modal dialog displayed on the edge of the webpage

I am facing an issue with a modal dialog that pops up when clicking on a thumbnail. The JavaScript code I used, which was sourced online, integrates a basic Bootstrap grid layout. The problem arises when half of the popup extends beyond the edge of the pa ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

What is the best way to add up values from text fields with the same ID?

I am working with input fields that are set up like this <input id="nilai" name="nilai" type="text" value="10" readonly /> <input id="nilai" name="nilai" type="text" value="10" readonly/> <input id="nilai" name="nilai" type="text" value="10 ...

Display notification only on certain days

I'm trying to create an alert that only pops up on specific days, but I can't seem to figure it out $(document).ready(function () { $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday&a ...

Choose2 - Dynamic search with auto-complete - keep track of previous searches

Currently, I am utilizing Select2 version 3.5.1 and have successfully implemented remote data loading with the plugin. However, I have a query regarding enhancing the search functionality. Below is a step-by-step explanation of what I aim to achieve: Cre ...

Invoke a function from within an event handler

Is there a way to trigger a function once an event has been completed? For example - $('.class').slideUp('fast', function() { // execute the function }); ...

Prevent leaving the body empty while populating a page with Ajax requests

I'm currently facing a dilemma at work. Our team is utilizing Bootstrap, jQuery, and a REST API to populate our web pages. Here's the sequence of events during page loading: The server receives a request A template is served which loads all ne ...

`Problem encountered in establishing a database table through jQuery ajax`

I am completely new to utilizing jQuery and ajax. Currently, I am experimenting with creating a table on my local MySQL server using a JavaScript file that sends SQL statements to a .php file for execution. Here is the code in the .js file: function exec ...

JSON retrieving a singular record exclusively

I am facing a dilemma with my code. When using a certain function, I retrieve hundreds of records but I am unable to add any additional information. Here is the code snippet: function(data){ $.each(data.products, function(i,item){ ...

Best practices for managing Ajax requests in ASP.Net MVC 3

When it comes to implementing Ajax calls in ASP.Net MVC, there are numerous options available for making calls, handling them on the server, and managing success and error scenarios on the client side. While some aspects have clear solutions, I have strugg ...

Using Ajax to update a webpage by invoking a PDO function within a PHP class

Looking for assistance with filtering a list of files using a dropdown box and categories. I have a PHP class ready to handle the SQL query and results, but I'm eager to implement this through AJAX to avoid page refresh. Feeling stuck and seeking gui ...

Adjusting the appearance of a label within an md-input-container using a CSS class

Looking for a way to apply styling to the md-input label inside md-input-container using ng-class. While able to style with inline css, encountering issues when trying to use a css class on the label. Is this expected behavior or am I overlooking somethin ...

Leveraging jquery's setInterval for automating tasks like a cronjob

I've been experimenting with Cronjobs and I've run into a roadblock. My goal is to have the cronjob execute every X minutes, containing a script with JavaScript that calls an ajax request every second for the next 60 seconds. The ajax call trigge ...

Remove numerous entries from the WordPress database by selecting multiple checkboxes

A new customer table named "tblvessel" has been created in the Wordpress database. The code provided below selects records from the database and displays them as a table with checkboxes next to each record, assigning the record's 'ID' to the ...

I am curious if there is a method to vertically center text without being affected by the font-family or font-size

Searching for a font-independent method to center text within a div. My div has a button-style fixed height, and I need the text (one line only) to be centered vertically within it. The issue arises when changing the font-family, as some fonts do not ali ...