Is it possible for jQuery to execute in a sequential manner?

Below is the code I am working with:

https://jsfiddle.net/c4zquo60/1/

CSS:

#bg {
    background-repeat: no-repeat;
    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    width:100wh;
    height:100vh;
    z-index: -1;
    opacity: 0;
    transition: opacity .25s ease-in-out;
}

jQuery

$(function() {
    $('#triggerModel').hover(function () {
        $("#bg").css({'opacity':0});
        $("#bg").css({'background-image': "url('backgroundModel.jpg')"});
        $("#bg").css({'opacity':1});
    });
});

$(function() {
    $('#triggerArt').hover(function () {
        $("#bg").css({'opacity':0});
        $("#bg").css({'background-image': "url('backgroundArt.jpg')"});
        $("#bg").css({'opacity':1});
    });
});

$(function() {
    $('#triggerDev').hover(function () {
        $("#bg").css({'opacity':0});
        $("#bg").css({'background-image': "url('backgroundDev.jpg')"});
        $("#bg").css({'opacity':1});
    });
});

My understanding of coding tells me that each line should execute sequentially. For example, shouldn't it set the opacity to 0 first with $("#bg").css({'opacity':0});, then change the background image with

$("#bg").css({'background-image': "url('backgroundModel.jpg')"});
, and finally restore the opacity to 1?

When the page loads, according to the CSS code, the background image has an opacity of 0 and no actual image loaded. Upon hovering over the element, it animates as expected. However, when I hover over another one of the three nav elements, the opacity easing is ignored and it immediately switches to the next background image.

Is there a way to make jQuery follow instructions in sequence? Should I introduce a delay between functions to allow for transitions? Or is jQuery failing to recognize the transition in the CSS code after the initial execution?

Answer №1

Don't forget to consider the delay you set in your CSS, as JS/jQuery is not aware of it.

For a better solution, you can utilize the mouseover() and mouseout() functions.

$(function() {
    $('#triggerModel').mouseover(function () {
           $("#bg").css({'opacity':1});
           $("#bg").css({'background-image': "url('https://i.imgur.com/QZ5H6bo.jpg')"});
    }).mouseout(function(){
           $("#bg").css({'opacity':0});
    });


    $('#triggerArt').mouseover(function () {
           $("#bg").css({'opacity':1});
           $("#bg").css({'background-image': "url('https://i.imgur.com/tS8WsBm.jpg')"});
    }).mouseout(function(){
             $("#bg").css({'opacity':0});
    });

    $('#triggerDev').hover(function () {
           $("#bg").css({'opacity':1});
       $("#bg").css({'background-image': "url('https://i.imgur.com/b4V9l6u.jpg')"});
    }).mouseout(function(){
             $("#bg").css({'opacity':0});
    });

});

You can check out an example closer to what you're looking for here: https://jsfiddle.net/mw3v49vt/

EDIT:

I made changes to the HTML/DOM structure: I replaced the id with a class, added the tag data-bgimg containing the background image link. With this setup, adding a similar effect elsewhere just requires changing the data-bgimg URL.

<div class="interactiveBackground" data-bgimg="https://i.imgur.com/b4V9l6u.jpg" style="float:right;">
      <a href="#"><img src="https://i.imgur.com/VrVx9iQ.jpg" alt=""/></a>
</div>

Reusable JS code: Selecting the interactiveBackground class, I use $(this) to target the currently triggered DOM object. By accessing its data-bgimg attribute, the value is stored in the background variable.

$(function() {

  $('.interactiveBackground').mouseover(function(){
        var background = $(this).attr('data-bgimg');
        $('#bg').css({'opacity':1});
        $("#bg").css({'background-image':"url('" + background + "')" });
  }).mouseout(function(){
        $("#bg").css({'opacity':0});
    });

});

Check out this modified version on jsFiddle: https://jsfiddle.net/02en3973/

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

Is it possible to apply styles to the body of a document using styled-components?

Is it possible to apply styles from styled-components to a parent element, such as the <body> tag, in a way that resembles the following: const PageWrapper = styled.div` body { font-size: 62.5%; } ` ...

Set a CSS rule to style every other row in a table, starting from the second row and resetting after

Is there a way to refresh the even and odd count in CSS whenever a specific row is shown? Here's an example setup: header header header even even even odd odd odd Subhead Subhead Subhead even even even How can I ensu ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

Preventing page refresh when typing in a form input: Tips and tricks

I'm currently puzzled by a small issue. In my web application, I have a chat box that consists of an input[type='text'] field and a button. My goal is to send the message to the server and clear the input field whenever the user clicks the b ...

When trying to load AJAX, it does not function properly unless the page is refreshed

I'm currently working on a web page and encountering some difficulties. Within my HTML, I have two divs that are refreshed using AJAX. The issue is that the content loading seems to be inconsistent unless I manually refresh the page or implement a tim ...

JavaScript - AJAX Call Terminated after a Period on Secure Socket Layer (SSL)

Currently, my AJAX calls over an SSL connection using the Prototype JS framework run smoothly initially. However, after 10 seconds of being live on the page, they start failing with a status of 0 or 'canceled' in the Network Inspector... This is ...

A guide to correctly importing a Json File into Three.js

I've been working on some cool projects in Blender and wanted to showcase one using threejs. However, I'm facing an issue where the object isn't displaying properly. Can someone guide me on how to correctly load a JSON file with keyframe ani ...

Would it be unwise to create a link to a database directly from the client?

If I want to connect my React app to Snowflake all client-side, are there any potential issues? This web app is not public-facing and can only be accessed by being part of our VPN network. I came across this Stack Overflow discussion about making API cal ...

Using Angular function to retrieve Firebase snapshot

Trying to access a user's profile image stored in Firebase at /user/[uid]/info/photoURL This is being done using Angular functions. Here is the code snippet: HTML: <img ng-src="{{getImg(user.uid)}}" alt=""> Javascript: $scope.getImg = func ...

Testing a function within a React functional component using jest.spyOn with React Testing Library can be accomplished with the following steps:

I'm currently working on a React component and I'm facing an issue with unit testing using React Testing Library. Specifically, I'm having trouble testing the handleClick function of the TestComponent using jest.spyOn(). Can anyone provide s ...

Customizing MaterialUI styles in React: A step-by-step guide

When utilizing Material UI with React, I am facing difficulty styling the Outline Select component according to my preferences. How can I override the default styles effectively? Even after using withStyles, I am unable to achieve the desired appearance a ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

Submitting an AJAX request to upload an XML file and an image file simultaneously in one call

I need to send both an uploaded image and an uploaded XML file to a PHP file using a single AJAX call. I have tried using two form data instances, but I am not sure if this is the correct approach. <input type="file" class="form-control-file" name="fil ...

Choose an option from the dropdown menu when clicking on the radio button

My issue involves a drop-down menu along with two radio buttons, each with two values: jQuery('input[type=radio][name=radio_type]').change(function(e) { var value = jQuery(e.target.value); jQuery('select[name="optType"] option:selecte ...

Check out this awesome jQuery Image Hover Plugin that allows you to create dynamic animations when hovering over other elements

Is it possible to use Adipolo in a way that allows hovering over a different element for the image animations to work? Currently, I am using the following code: $('#img-caption-one').adipoli({ 'startEffect' : 'grayscale' ...

Convert JSON data without backslashes using json_encode

I am having an issue where I retrieve a JSON encoded array from the database, modify one field, and then save it again. However, when I use json_encode, it removes the backslashes and as a result, the text is not displayed correctly on my site. $data_de=j ...

Check if the parent element has a specific class, and if so,

I am trying to achieve a functionality where clicking on an element will add a class, but if the parent of this element already has the class, it should remove it first. However, the current code is not working as expected. It only adds new classes without ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

Information about the HTML detail element in Angular 2 is provided

Hi, I'm curious if there's a way to know if the details section is open or closed. When using <details (click)="changeWrap($event)">, I can't find any information in $event about the status of the details being open. I am currently wor ...

"Error encountered when attempting to upload directory due to file size

Utilizing the webkit directory to upload a folder on the server has been successful, however, an issue arises when there are more than 20 files in the folder. In this scenario, only the first 20 files get uploaded. The PHP code used for uploading the fold ...