Alter the background image of items upon hovering over an item in a dropdown menu

Hey there! I'm currently working on a project using Bootstrap and have a simple navbar header that contains two dropdown menus with items. However, I now need to modify it to include sub-menu items with associated content, similar to the example below. When hovering over a sub-menu item, I want to change an image to display a car related to that specific item. For instance, hovering over item 1 would show one type of car, while hovering over item 2 would show another. All of this should be contained within the sub-menu items...

This is my current code:

<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle page-scroll" href="#" id="navbarDropdown" role="button"
                        aria-haspopup="true" aria-expanded="false">About Us</a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
       <a class="dropdown-item" href="#item1"><span class="item-text">Item 1</span></a>
    <div class="dropdown-items-divide-hr"></div>
         <a class="dropdown-item" href="#item2"><span class="item-text">Item 2</span></a>
    </div>
</li>

https://i.sstatic.net/7iNAS.png

Answer №1

When using JavaScript, you can achieve the following:

document.getElementsByClassName('item-text')[0].addEventListener('mouseover',function(){
document.getElementById('carImage').style.display = 'block';
document.getElementById('carImage2').style.display = 'none';
});
document.getElementsByClassName('item-text')[1].addEventListener('mouseout',function(){
document.getElementById('carImage2').style.display = 'block';
document.getElementById('carImage').style.display = 'none';
});

Remember to include your <script> tags and ensure to replace "carImage" and "carImage2" with the actual IDs of the images in your HTML code.

Answer №2

If you prefer not to load all the images when the page loads (to conserve bandwidth on mobile devices and speed up the page loading process), another alternative would be to assign a data-attribute that contains the URL of the image you want to display for each link. Then, using Javascript or jQuery, you can modify the style of your image container to show the correct image when hovering over the respective link.

Here is an example code snippet:

const defaultImage = 'http://lorempixel.com/g/400/400/';

$('[data-background-image]').on('mouseover', (e) => {
  const imageToShow = $(e.currentTarget).data('background-image');
  $('#my-background-image-container').css('background', `url(${imageToShow ? imageToShow : defaultImage})`)
})

$('[data-background-image]').on('mouseout', (e) => {
  $('#my-background-image-container').css('background', `url(${defaultImage})`)
})
#my-background-image-container{
  width: 200px;
  height: 200px;
}




Content

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 could be causing the issue with the width: 100% not rendering correctly in this

I'm currently working on my footer, but I'm having trouble getting the width: 100% tag to work correctly. Here's a screenshot of what I mean: http://gyazo.com/9c23897cd7b9a74ca55ee9fb977f810c This is my CSS code: /*..Portfolio - Lars Beut ...

The jQuery method serializeArray does not include the values of HTML textareas and checkboxes

Hello, I'm looking to send data to the server from an HTML form. The server I'm using is CodeIgniter and I'm utilizing the AJAX method. Here's the HTML form: <div id="fileupload"> <form id="upload-media-form" class="uploa ...

Altering an element's visibility from 'none' will trigger its animation to play once again

Take a look at the snippet below and you'll see that the sliding animation plays twice - once when the .addClass statement runs, and again when #test's display is switched to 'initial' (timeouts are in place to help visualize the issue) ...

Use a positioning method that places items at the top of the container and evenly distributes the space

I'm working on aligning the black boxes at the top of the container in my html code. I want the content to be responsive so that when the window size decreases, the images move down and justify themselves like 'justify-content-between' for t ...

utilize jQuery to include a tag into every div

This is the current sample: <div class="main-wrap"> <div class="inner-wrap"> some example text here <span> <a href="1">test1</a> </span> </div> <div class="inner- ...

Can pagination numbers in Jquery DataTable be configured based on the total records returned by the server and the number of records chosen by the user?

I am currently diving into the world of DataTable.js, a jQuery plugin, and working hard to articulate my questions effectively. For my specific needs, I need to retrieve only 10 records initially whenever an AJAX request is made, even if there are 100 rec ...

Should the autonomous function be halted upon user interaction?

I am working on a carousel that automatically runs, but I also want it to reset its timer if a user interacts with the controls. The current setup does work to some extent, but when interacting with the control-dot, the timer is not reset which leads to un ...

What is the best way to create a complete margin separation between two unrelated elements?

Here is the code snippet I am currently working with: HTML <div class="container"> <div class="limit"> &nbsp; </div> <div class="dots"> &nbsp; </div> </div> CSS .container { background-colo ...

Is the isPointToPath function unreliable in JS/CANVAS/HTML?

Check out the snippet below for testing purposes. The yellow(y) area represents the canvas, returning "n" upon clicking The red(r) area represents the clickable region, returning "y" upon clicking The trouble(x) area indicates an error, returning "y" wh ...

Disable button not necessary when validating checkboxes

I'm working on a simple function that involves 3 checkboxes. The goal is to disable the button if all checkboxes are unchecked, and enable it only when all three checkboxes are checked. function checkAll() { var checkbox1 = document.getElem ...

How can I create a dynamic chart with jQuery Flot?

Currently immersed in working on the jQuery Flot plugin and I've hit a roadblock. Anyone know how to seamlessly integrate new data into my charts? Your assistance would be greatly appreciated, thank you! ...

How can I use Ajax to show only one div on the entire page while keeping the CSS and other header content intact

One of my clients is looking to integrate a merch shop into their website. The existing merch page is not visually appealing and doesn't match the aesthetic of the client's site. I am considering using AJAX GET to fetch the content of the merch p ...

Tips for referencing a function declared within a prototype

I have been attempting to enhance a web page by adding functionality using a jquery library that lacks documentation. The problem I am encountering is primarily due to my lack of understanding of the jquery plugin model and/or the inner workings of javascr ...

Maintaining binding while appending inner elements within a container using jQuery

I'm struggling to transfer the contents of one container to another without losing any bindings, and it's proving quite tricky! <div class="container"> <div class="field"> <label>Username</label> < ...

Implementing the bootstrap dynamic modal in Laravel Blade for delete confirmation is an effective way to enhance user

I'm aiming to utilize a bootstrap modal for delete confirmation. However, I'm facing an issue where I need to pass a dynamic variable (containing the item ID) value to the bootstrap modal in order to submit a post request to delete that specific ...

Is it possible to have the background scroll downward while keeping some content centered in place at all times?

Attempting to achieve the following effect in JavaScript, HTML, and Sass: When scrolling down the page, the layers (ground, sky, space, etc.) move downward The content (a rocket flying in the sky) stays centered on the screen and will move horizontally l ...

Jquery-Tools Tabs AJAX Caching: almost within reach but slightly out of grasp

Wow, JqueryTools Tabs is truly impressive [http://flowplayer.org/tools/demos/tabs/ajax.html]. However, the downside is that these tabs with AJAX functionality do not cache. This means a fresh reload every time you click on a tab. We're getting closer ...

Ways to toggle the expansion and collapse of multiple divs efficiently with jQuery without duplicating code

I am trying to create a script that will expand and collapse a div containing a paragraph when the header text above it is clicked. <div class="container"> <h3><span class="toggler">Click here to toggle text</span></h3> <d ...

What is causing the CSS loader to continue showing up even after all the items have finished loading?

I have been developing an innovative newspaper/blogging platform using CodeIgniter 3.1.8 and Twitter Bootstrap 4. Currently, my focus is on implementing the AJAX functionality to load more posts dynamically. The default setup paginates the posts, display ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...