Modify jQuery to update the background image of a data attribute when hovering over it

Something seems to be off with this topic. I am attempting to hover over a link and change the background image of a div element. The goal is to always display a different picture based on what is set in the data-rhomboid-img attribute.

<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
            <ul class="menu-list"> 
                <li><a href="#" data-rhomboid-img="img/example1.jpg">A</a></li>
                <li><a href="#" data-rhomboid-img="img/example2.jpg">B</a></li>
            </ul>

.nav-rhomboid{
    background: url(../img/nav-bg.png) no-repeat center center;
    display: flex;
    align-items: center;
}

 $('li a').mouseover(function () {
    var rhomboidImg = $(this).data('rhomboid-img');

    $('#img-nav-rhomboid').each(function () {
        $(this).css('background', $(this).attr(rhomboidImg));
    });
});

Answer №1

Feel free to try out this line of code

$('#img-nav-rhomboid').css('background', 'url(' + rhomboidImg + ') no-repeat');

$('li a').mouseover(function() {
  var rhomboidImg = $(this).data('rhomboid-img');
  $('#img-nav-rhomboid').css('background', 'url(' + rhomboidImg + ') no-repeat');
});
.nav-rhomboid {
  background: url('http://s7d2.scene7.com/is/image/PetSmart/PB0101_HERO-Dog-Toys-20160818?$sclp-banner-main_large$') no-repeat center center;
  display: flex;
  align-items: center;
}

#img-nav-rhomboid {
  height: 200px;
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list">
  <li><a href="#" data-rhomboid-img="https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg">A</a></li>
  <li><a href="#" data-rhomboid-img="img/example2.jpg">B</a></li>
</ul>

Answer №2

Your jQuery code contains an error, please see the corrected snippet below:

 $('li a').mouseover(function () {
    var rhomboidImg = $(this).data('rhomboid-img');
    $('#img-nav-rhomboid').css('background', 'url('+rhomboidImg+') no-repeat');
});
.nav-rhomboid{
    background: url(../img/nav-bg.png) no-repeat center center;
    display: flex;
    align-items: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list"> 
    <li><a href="#" data-rhomboid-img="img/example1.jpg">A</a></li>
    <li><a href="#" data-rhomboid-img="img/example2.jpg">B</a></li>
</ul>

Answer №3

Here are some tips to help you out:

1- Make sure to add height and width to the nav-rhomboid div using CSS

2- Remember to include url() in your JavaScript code for the css line

3- Avoid looping over elements with the same ID (IDs should be unique)

4- Update the code with the correct path to images (tested on my end with one image)

<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list"> 
    <li><a href="#" data-rhomboid-img="images/back_release.jpg">A</a></li>
    <li><a href="#" data-rhomboid-img="images/back_investors.jpg">B</a></li>
</ul>
<style>
.nav-rhomboid{
    background: url(images/back_reset.jpg) no-repeat center center;
    display: flex;
    align-items: center;
    min-height: 400px;
    width: 100%;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
 $('li a').mouseover(function () {
    var rhomboidImg = $(this).data('rhomboid-img');
    $('#img-nav-rhomboid').css('background', 'url('+rhomboidImg+')');
});

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

Using Jquery to extract URL parameters

Can anyone suggest a jQuery function I can use to fetch URL parameters? I've been utilizing the following function, which works well; however, it encounters issues when the URL doesn't have any parameters. I would like it to return an empty stri ...

Press the AngularJS button using just JavaScript and the element

I've been developing a browser extension that automatically clicks buttons on web pages, but I've run into an issue with sites using AngularJS. The code functions properly on most websites except for those built with AngularJS. Below is the snip ...

Error: Firebase is not recognized as a valid function

I have been attempting to go through the firebase Node tutorial at this URL: Running my node.js app leads to a crash with a "TypeError: Firebase is not a function" error. Here is an excerpt from my index.js file: var Firebase = require("firebase"); var f ...

Steps to revert table data back to its original state after editing in Angular 12 template-driven form

Currently, I have implemented a feature in my web application where users can edit table data by clicking on an edit hyperlink. Once clicked, cancel and submit buttons appear to either discard or save the changes made. The issue I'm facing is related ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

Tips on transferring values from script to controller in PHP using Laravel (for beginners)

I am trying to update the value in a textbox using a script and then save it in my database through my controller. Although the value in the textbox changes, the ajax call does not work as expected. I apologize for any mistakes, as I am still new to this p ...

Setting radio button values according to dropdown selection - a beginner's guide

I am trying to dynamically set the default values of radio buttons based on the selection made in a drop-down menu. For example, if option A or B is chosen, I want the radio button value to default to "Summary", and if option C is chosen, I want the value ...

Getting the value from a dropdown menu and displaying it in a text area

I have 3 functions (radio, textarea, and dropdown) I was able to successfully retrieve the values of radio and textarea into the textarea. However, the drop down functionality is not working as expected. My goal is to display the selected option from the ...

Is there a TypeScript alternative to triggering a click event on a specific class using $(".class").click()?

I am currently utilizing a date range picker within an Angular project. <button type="button" class="btn btn-danger daterange-ranges"> <i class="icon-calendar22 position-left"></i> <span></span> <b class="caret"></b ...

What methods can be used to ensure that the variable $ can serve as both an object and a function?

One interesting feature of jQuery is how the variable $ can function as both an object and a function. // For example, you can access object properties like $.fn; // or $.isReady; // You can also call the function $ like this $(); So, how can we make the ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

Steps for displaying the contents of a file from Firebase storage on a React component

I uploaded a file to Firebase storage, and I want my app to be able to access and display the contents of that file within my class component div. Currently, when I try to access the file, it just opens in a new tab instead. class ScanResult extends Comp ...

What methods can be used to assess the security risks posed by a third-party library implemented in a React JS application?

How can I ensure the security of third-party libraries added to my create-react-app with additional scripts? ...

Sending Objects Array in POSTMAN using Hapijs: A Step-by-Step Guide

Could you please assist me on how to send a POST request in POSTMAN for the given array of objects and then validate it using Joi in a hapi server? var payload = [{ name: 'TEST Name 1', answer: 'TEST Answer 1', category: &a ...

Unable to access the following element using jQuery's next() method

Can someone help me understand how the "next" function works in jQuery? I'm trying to reveal a hidden textarea when a span element is clicked. The hidden textarea is supposed to be the immediate next sibling of the span, but it's not working as e ...

Is the HTML5 capture attribute compatible with wkwebview?

Is it supported as stated in the title? For more information, you can check out the MDN documentation (Incomplete) and the Caniuse list of supported browsers. Surprisingly, none of them mention wkwebview. Does this attribute have support in wkwebview? Kno ...

The value of the checked input with the name `nameofinput` is currently not defined

I'm having trouble passing the input value to another page. $( this ).attr( "href", '?module=module_progress_report&Subject='+ $('input[name=subject]:checked').val()+ '&Centre_Selected_ID='+ encodeURIComponen ...

Connectivity issue: Socket.io fails to register user upon connection

Upon connecting to the page, I expect to see the message 'a user connected' printed on the command line using node.js. However, this message is not being displayed, indicating that the user's visit to the page is not being registered (all ac ...

Sticky positioning and outline effects

I have been working on creating a scrollable list with "sticky" headers. The functionality seems to be in place, but there are some visual glitches that I've encountered. The list itself is structured using a ul element styled with the Bootstrap 5 cl ...

How can I use a button to programmatically activate the update callback function of a sortable widget?

In the example provided in this jsbin, there is a sortable list and a button. When the button is clicked, something is added to the sortable list. The goal is to determine which event of the sortable list is fired (update or receive) and then perform a spe ...