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

What is the functionality of {all: initial} and how does it address issues with default values?

Why do paragraphs inherit properties like line-height and text-align from the div element? If values for these properties are: normal -> for line-height [i.e. font-size = 16px (initial / default value) * normal (value is usually around 1.2 -> 19.2 ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

Verifying the numerical value of a decimal place

How can I determine if the 4th decimal place in a number is zero or not? I want to throw an error message if it is not zero. For instance, in the number 2.3189, the value of the 4th decimal place is 9. My current code works for most cases, but for exampl ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Locate relevant information within the arrays through the process of filtering

For my collection, I am looking to match the operator_name based on date and then further narrow it down by matching shift_name within an array { "_id": "5eb301bc0218ff48b724a486", "date": "2020-07-02T00:00:00.000Z", "shift_wise": [{ "_id": ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

Moving a Node project to a different computer

I am looking to transfer my Angular project from a Windows machine to a Mac. I attempted to copy the folder and run npm install, but encountered an issue. Here is the error message I received: sh: /Users/pawelmeller/Documents/hotel/angular4/node_modules/ ...

Reading an XML file to locate items nested within the same bracket

Within my JavaScript function, I am utilizing the following code to extract data from an XML file: var title = $(this).children('Title').text(); This snippet of code successfully retrieves the content under the <Title> tags: <Title> ...

Updating the configuration settings for CKEditor 5 using Reactjs

I followed the configuration provided in another answer at But, I am facing an issue: Failed to compile. ./src/components/cards/CreateCard.js Line 59:22: Parsing error: Unexpected token, expected "}" 57 | editor={ClassicEditor} 58 | ...

Unable to fetch options for drop-down list from Database

As someone who is new to frontend application development, I am facing a challenge in populating a Select list from the database. Despite following similar approaches like the one discussed in How to populate select dropdown elements with data from API - R ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

Error message: The variable "data" is not defined in next.js

Being new to React, I recently used getStaticprops to retrieve data from an API for a filter gallery project. However, I encountered an issue when trying to access the {props: data} outside of the blog function - it resulted in a Reference Error stating th ...

What is the best way to showcase a blank div element using CSS?

Is there a way to make this empty div tag display without having to add &nbsp;? Can it be achieved using only CSS? <div class="bar bg-success" title="2015-07-23,5.0000" height="50%"></div> .bar { background: green; width: 5px; float ...

The form-group nested within a form-horizontal is exceeding the boundaries of the preceding form-group

I am currently utilizing Bootstrap 3.3.6 and have a basic form enclosed in a panel: https://i.stack.imgur.com/UOFI6.png Although it is quite simple, the alignment of the "Post" button is not displaying properly. Here is the HTML code for the form: < ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

Displaying separate items onto a webpage based on their unique identifiers

Currently, I am in the process of developing a JavaScript web application that retrieves input from a user (specifically the name of a music artist) and then produces a list of related artists along with their most popular songs, all thanks to information ...

Is it possible for me to sum up each row in the table and then deactivate it using a checkbox?

I am facing an issue with my code. The problem arises when I utilize the each() function; it iterates from the first cell to the end of the row, fetching every value along the way. What I actually want is for it to retrieve the value from each row individu ...

Encountering the issue of "Unknown provider" while injecting Angular modules

After following a tutorial on organizing an Angular project, I came up with a structure where I have a ng directory containing all my controllers, services, and the routes.js file. These are then bundled together into an app.js through my configuration in ...

Discover how to access the translations of a specific key in a chosen language by utilizing the angular $translate functionality

How can I retrieve a specific language translation using angular's $translate function within a controller? The $translate.instant(KEY) method returns the translation of the specified key based on the currently selected language. What I am looking for ...

JavaScript code encounters a math calculator script error

Am I overlooking something in my script? Everything seems to work fine when I click the minus (-) button, but when I press the plus (+) button, the calculator malfunctions. It displays 1, 11, 21, and so on, all ending with 1... Here is my code: functi ...