Using jQuery to define active or hover background images

I'm currently working on a list containing 5 items, with the first one active by default (thanks to jQuery adding a 'active' class). Each item has its own background image. When I click on any of the list items, another div gets updated with relevant content.

However, I'm facing a challenge:

I want to achieve the following behavior - when an item is clicked, its background image should change to color (using the '-cl.png' suffix). If I hover over another item, its background image should also change to color, while keeping the previously clicked item in color as well. Any item that is not hovered over should display a black and white version of the background image (with the '-bw.png' suffix), except for the active item which should remain in color.

I hope this explanation makes sense. Any suggestions on how I can implement this? Thanks, Brett

Below is my HTML:

<ul class="graduate_tab">
<li class="graduate1"><a href="#grad1"><span class="gradimg1">grad1</span></a></li>
<li class="graduate2"><a href="#grad2"><span class="gradimg2">grad2</span></a></li>
<li class="graduate3"><a href="#grad3"><span class="gradimg3">grad3</span></a></li>
<li class="graduate4"><a href="#grad4"><span class="gradimg4">grad4</span></a></li>
<li class="graduate5"><a href="#grad5"><span class="gradimg5">grad5</span></a></li></ul>

Answer №1

To start, the majority of the work can be done in CSS to style elements as needed:

.graduate1 { background: url(image1-bw.png); }
.graduate1.active, .graduate1:hover { background: url(image1-cl.png); }
.graduate2 { background: url(image2-bw.png); }
.graduate2.active, .graduate2:hover { background: url(image2-cl.png); }
//etc...

Then, in jQuery, you only need to focus on managing the 'active' class like so:

$('.graduate_tab li').click( function() {
  $(this).addClass('active').siblings().removeClass('active');
});

By using .addClass() for the clicked element and .removeClass() for the others, you can easily toggle the 'active' class. If you want to remove it from an already active element (toggle off), consider replacing .addClass() with .toggleClass() for that functionality.

Answer №2

$('.graduate_tab li').mouseover(
  function() {
    $(this).css('background-image','hover-image-cl.jpg');
  }, function() {
    $(this).css('background-image','hover-image.jpg');
  });

$('.graduate_tab li').on('click', function() {
  $('.graduate_tab li').removeClass('active');
  $(this).addClass('active');
});

This code should work for your needs. If there are any modifications needed, feel free to let me know.

Answer №3

Instead of assigning classes to each li element in CSS, I utilized the click hover jQuery function:

.ui-state-active, .ui-state-hover  {
    font-weight: bold !important;
    //and other css
}

Furthermore, I implemented this code:

 jQuery('.graduate_tab li').bind('click hover', function () {
        jQuery(this).addClass('.ui-state-active')
                    .siblings().removeClass('.ui-state-active');

 });

I hope this solution proves beneficial for someone else as well.

Answer №4

To create hover effects in CSS, you can use the :hover property.

For example:

:hover {background-color: red;}

This code snippet will change the background color to black when hovered over, but be cautious as it may not work in older browsers like IE6.

Answer №5

    $('.titleclz').mouseover(function( event ) {

    $(this).css('background-image','url(image-hover1.png)');
    $(this).css('background-repeat','no-repeat'); 

});

$(".titleclz").mouseout(function( event ) {

    $(this).css('background-image','url(image-normal.png)');
    $(this).css('background-repeat','no-repeat');

});

Create JQuery hover effect for changing background images...

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 best way to implement client side validation for a related input field using JavaScript in a Rails application?

Struggling to find a solution for adding a validation check for a dropdown list that is dependent on another input selection in a different form. It seems like database validation may be necessary, but I'm unsure of the best approach. Any suggestions ...

Firefox presents a compact box positioned between the images

When attempting to use flags as a way to switch between languages, I encountered an issue in Firefox where a small box appears between the images on the Hebrew site. In Chrome, everything works fine. I implemented the following code: <div class="flags ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

In JavaScript programming, the function is always executed after the bottom code

I am currently working on a piece of code that is partially functional. The purpose of this code is to verify the existence of an email address in a database. If the email does not exist, it should return true; $(document).ready(function() { var ema ...

Dynamically enhance dropdownlist options in webforms using JavaScript

I am currently working on an asp.net webforms project where I have a page with 2 dropdown lists. Whenever a user selects an option from ddl1, I want to dynamically add that selected element to ddl2 using JavaScript. Initially, when the page loads, ddl1 h ...

Chrome is the only browser that displays the correct number of columns, unlike IE and Firefox

[Link removed] Is anyone else experiencing an issue with the columns on a website layout? I have 5 columns set up with each post taking up 20% width. It looks fine in Chrome, but in IE and Firefox, the last column gets pushed below so there are only 4 col ...

Expanding the size of the number input in Twitter Bootstrap to accommodate changing content dimensions

I have a numeric input field that I want to customize in terms of width. I need the field to start with a minimum width so that -1, the default value, fits nicely inside. As the value changes, whether decreasing to -100 or increasing to -1,000 and beyond ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

PHP does not provide any error when an update on a database row fails

When I try to update values retrieved from the database into a form on submission, the process fails without any error message. Below is the PHP code snippet: <?php session_start(); $username=$_SESSION['uname']; $cn=mysqli_connect("loc ...

Using jQuery UI to create sortable lists that are connected and have hidden overflow features

How can I hide overflow from two fixed-height divs containing sortable lists connected to each other without affecting their connection? For example, if overflow is set to hidden, the list item doesn't display when dragged outside of the div. I' ...

Modify a number with a check box using inline Ajax

I have an HTML structure similar to this example: <li><label class="desc"><font color="green">Want to receive emails ($<span id="price">50</span>/month)</font></label> <input type="checkbox" checked ...

Applying a Webkit Scroll Bar to a specific element on the webpage

I've been attempting to apply the Scroll Bar webkit styling to a particular element but haven't had any success. Despite searching extensively, I have come across 2 threads on Stack Overflow that do not provide a solution. Most of the available ...

Animation not functioning properly after Ajax call in event onload

After making an AJAX call to load all the data, I encountered an error in the response data. The code snippet likeObj('#like'+postid).effect("bounce", {times:1,distance:25},400); throws an error stating that likeObj is not a function. I'm s ...

When making a request for "/example.php/" the CSS does not seem to take effect, however, the content is displayed properly

Currently, I am working on a PHP script where I have divided each section into separate .php files and included them using the include() function. Here is an example of how everything is set up in different folders: header.php footer.php etc.. When acc ...

Showing information from a table for editing purposes with the use of HTML input tags

As I navigate my way through the complexities of HTML and PHP coding, I’m faced with a challenge in displaying database content on an editable table within my web page. Clicking the edit button should lead to a separate page where data can be modified. ...

WordPress CSS Styling Issue: HTML Element Display Problem

I recently converted my static HTML site to WordPress, but I'm facing an issue where the site is always aligned to the left. Despite trying different solutions like the one below: body{ margin: auto; } The original HTML page was centered perfectly ...

Organizing grid elements within the popper component

I am struggling to align the labels of options in the AutoComplete component with their respective column headers in the popper component: https://i.stack.imgur.com/0VMLe.png const CustomPopper = function (props: PopperProps) { co ...

The Jquery map function is not returning selected options, always returning empty values. It seems to be avoiding the variable, although it functions properly on jsfiddle. There are

RESOLVED: Final solution: http://jsfiddle.net/AcfUz/220/ *applied the selector mentioned in the selected answer and adjusted the console.log value to appear before the text input, where the chosen options were supposed to be displayed, and voila--it&apo ...

How to include <li> in a preexisting <ul> using JSON data in jQuery

Here is the code snippet I am currently working with: <div id="tags"> <ul> </ul> </div> I want to add some items to the list using JSON data $.getJSON("data.json", function (data) { var html = ''; ...

jQuery Conditional String Manipulation

I have set up a system where users can input values and make selections from a drop-down menu, which then get integrated into JavaScript code to generate customized sentences based on their inputs. Once the user clicks submit, the sentence is formed. It&ap ...