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

Error encountered when using the module export in Node.js

I have a file named db.js which contains the following code: var mysql = require('mysql2'); var mysqlModel = require('mysql-model'); var appModel = mysqlModel.createConnection({ host : 'localhost', us ...

AngularJS Module Instantiation Error

My angularjs module is not loading correctly and I'm struggling to figure out why. Despite reading numerous tutorials, I can't seem to get it to work. [17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due t ...

When accessing nested objects in Props in Vue.js, an error may occur if the property of null/undefined

When I make an axios call, I receive an object which I pass to a child component. However, when I attempt to loop through the object in the child component to access a property of another nested object, I encounter an issue where the property is showing as ...

Having trouble with the CSS positioning of divs created with JavaScript: it's not behaving as anticipated

Let me start by saying I have always struggled with CSS positioning. It seems like I am missing something simple here... So, I have a JS script that generates divs within a parent container called #container which is set to absolute position. Here is the ...

Developing an interactive input tab for user engagement

I'm in the process of developing a web application for my current university workplace. Currently, I am seeking guidance on how to create a dynamic user input form for our website using asp.net and c# in visual studio 2017. I'm struggling a bit w ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

Preventing Click Events during Data Fetching in React.js without Using jQuery

In the redux store, there is a state called isFetching. When data is being fetched from the backend, this state becomes true. I need to disable all click events when isFetching is true, without using jQuery. I stumbled upon some solutions (involving jQuer ...

Should the username be specified but the password left blank, then an error message will be shown

<div class="form"> <h1>Sign In</h1> <form action="" method="post" name="login"> <input type="text" name="username" placeholder="Enter username" required /> <input type="password" name="password" placeholder="Enter password" ...

What is the best way to implement a conditional check before a directive is executed in Angular, aside from using ng-if

I am facing an issue where the directive is being executed before the ng-if directive. Is there a way to ensure that the ng-if directive is executed before the custom directive? Could I be making a mistake somewhere? Should I consider using a different ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Protractor Encounters Error When Assigning Variable

var itemStatus = element(by.model('item.statusId')).getText(); This issue is causing Protractor to raise an error: Uncaught exception: Error while waiting for Protractor to sync with the page: "Angular could not be found on the window" Pro ...

Stylesheets per module in Angular 2

For my website design, I've decided to adopt a modular structure using sass. To ensure consistency throughout the module, instead of defining stylesheets at the component level, I plan to define them at the module level and import them into each compo ...

Click to open the file browser by using the onclick event in Material-table actions

Currently, I am working with a Material table component from "@material-table/core" My goal is to implement an action that enables users to upload a file within this table. I am facing some challenges on how to trigger the file browser when the ...

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...

Is your jQuery TextEditor not functioning properly?

Having some trouble integrating the jQuery TextEditor plugin into my CodeIgniter project. I'm puzzled as to why it's not functioning properly. Just a heads up, my project also utilizes Bootstrap. Can anyone shed some light on why the plugin is fa ...

Inconsistent functionality: Twitter Bootstrap tabs malfunction when placed inside a modal

Within a rails application, I have successfully implemented loading the content of a modal window (bootstrap modal) using Ajax. The challenge arises when trying to integrate tabs (bootstrap tabs) within this loaded content. While the tabs are displayed co ...

Responsive Grey Tiles for Google Maps v3

I've successfully implemented Google Maps V3 in my project, but I'm encountering an issue with grey tiles appearing on the map. I attempted to fix this problem by triggering a resize event using the following code snippet: google.maps.event.trig ...

What is the best way to align HTML elements in a single row?

I have the following code snippet... <div class="header"> <div class="mainh"> <div class="table"> <ul> <li><a>smth</a></li> ...