Switching the background image with a single click and reverting it back with a double click using jquery

I am working on a project with multiple div elements which need their background images to change upon clicking and revert back to the original image when clicked again. Below is the CSS code for one of the divs, including its Class and ID:

.tab_box
{
width:2%;
height:20%;
position:absolute;
left:100%;
}

#tab_box1
{
background:url('cars.png') no-repeat center center;
background-size:120%;
-moz-background-size:120%;
-o-background-size:120%;
-ms-background-size:120%;
}

There are 3 other divs using the same "class" but with different "id" attributes to assign unique background images.

I attempted to use toggleClass in jQuery/CSS to achieve this functionality, but it doesn't seem to work as expected:

.one
{
width:2%;
height:20%;
background:url('mots.png') no-repeat center center;
background-size:120%;
position:absolute;
left:100%;
}
<script>
$(document).ready(function(){
$('#tab_box1').click(function() {
$('#tab_box1'').toggleClass("one")
});
});
</script>

If you have any suggestions on what I might be doing wrong or any alternative methods to achieve the desired image switching behavior besides toggleClass, please let me know!

Answer №1

The reason for this issue is due to the precedence of CSS rules, where the id rule takes precedence over the class rule.

In this scenario, the background image is set using the id rule #tab_box1, and then an attempt is made to modify it using a class rule .one.

One way to address this is by using !important in the class rule like below:

.one {
    width:2%;
    height:20%;
    background:url('http://placehold.it/32/f00000') no-repeat center center !important;
    background-size:120%;
    position:absolute;
    left:100%;
}

Check out the demonstration here: Fiddle

A better solution would be to use classes instead of ids as shown below:

<div class="tab_box tab_box1">sadfsdf</div>

Instead of

<div id="tab_box1" class="tab_box">sadfsdf</div>

Then apply your styles to the new classes like this:

.tab_box1
{
background:url('cars.png') no-repeat center center;
background-size:120%;
-moz-background-size:120%;
-o-background-size:120%;
-ms-background-size:120%;
}

See the demonstration: Fiddle

Answer №2

If you want a div to act like a button, you can have it switch to a different image when the mouse is clicked down, and then return to the original image when the mouse button is released.

$("#button1").mousedown(function() {
    $(this).css({'background-image': 'url(image2.jpg)'}) 
}).mouseup(function(){
    $(this).css({'background-image': 'url(image1.jpg)'}) 
});

HTML:

<div id="button1" style="background-image:url('image1.jpg');"></div>

Sources/References:

CSS background-image - What is the correct usage?

changing the background image on mouse down

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 my jQuery script to not load properly on the first attempt?

I have a jQuery script set up on this particular webpage just before the ending body tag. Here is the script: <script> $(document).ready(function(){ var demomain = $(".demo-bg section"); var demomainW = demomain.height()+ 150 ...

Conceal elements within a div using the 'elementFromPoint' function

In my HTML, I have a div that contains an icon and some text. I want to make it so that when I hover over the div with my mouse, only the div itself is visible to the 'elementFromPoint' function. How can I achieve this? Here is an example of th ...

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

Switch effortlessly between one animation and another with Angular.js

I have two animations named "prev" and "next". Upon clicking the prev button, the "prev" animation should play. Similarly, when you click on the "next" button, the "next" animation should be triggered. I am using ng-class to achieve this behavior. How can ...

Reinitialize the bootstrap modal every time it is closed to ensure a fresh start and maintain consistent functionality

$(".modal").on("hide.bs.modal", function(){ $(".modal-bodydata").html(""); }); In my application, there is a feature where users can upload images related to a book. Once the images are uploaded successfully, the modal closes and the contents displa ...

What can be done to improve the elegance of this jQuery function?

I am facing an issue on my webpage where I have a drop-down select box with a default value of (empty). The problem arises when the user selects an entry, and the appropriate form for that entry type should be displayed. However, there are a couple of iss ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

What is the best way to display a responsive website design exclusively for certain devices?

My website currently lacks responsiveness. Typically, we can check if a website is responsive by resizing the browser to see if it adjusts using CSS3 media queries. However, I am looking to create a better user experience by ensuring that visitors using a ...

Updating user credits through the Model::factory() method is a common practice in my workflow

I need to update the UserCredits after a purchase. For example, if a user currently has 10 credits and purchases 10 more, I want to add the purchased credits to their existing total. The goal is to increment the current credit score with the new credits ...

What is the best way to create a fixed contact form on specific pages?

There is a Contact Form 7 on the webpage that I want to make fixed to the right side. Initially, the form is hidden and only the form button (open) is visible. When clicked, the form should open. ...

Transmitting data via POST method within datatables ajax call

I am facing an issue while attempting to execute a simple ajax call in datatables that relies on a post array of IDs from a form on a previous page. The error I encounter is: Invalid JSON Response This indicates that the JSON array being returned may be ...

Extract the innerHTML input value of each row in an HTML table

I've encountered an issue with my HTML table that contains static values, except for one cell which has an input field. When I try to convert the row data into JSON, the single input field is causing complications. Without the input field, I can suc ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

Minimize the gap between the input text and the lower border

Is there a way to bring the input text field and text closer together by reducing the space between the bottom border and the text? #a { padding: 1px 3px; background: transparent; border: 0; outline: 0; border-bottom: 0.8px soli ...

Combining jqueryUI autocomplete and datalist for enhanced user input options

My search form in HTML has a single input field where users can enter three different things: area name, trek name, or other keywords. For areas not in a database, I have implemented a datalist field (HTML) connected to the input for autocompleting the a ...

What is the technique for using JavaScript to implement styling on a <td> within an HTML table?

Can someone help me with applying JavaScript to an entire column in an HTML table? Here is the script I am currently using: I want to insert a line break after each comma in the Message column of the table. Can anyone point out what I'm doing wrong? ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

How can I resolve the vertical adjustment issue of Bootstrap 5 input group on mobile devices?

My current issue involves using Bootstrap 5.2.3 to create an input group that displays a set of spans with the ".input-group-text" class alongside inputs with the ".form-control" class. While this setup works well on a computer screen, it does not adjust c ...

Retrieve HTML content from a JSON object and render it on a web page

I am facing a challenge with decoding html that is in json format. I'm struggling to figure out how to retrieve my html and display it on a page. It seems like json_decode isn't the solution. Can anyone help me with this issue? Appreciate any as ...

First-character styling not applying to ID in CSS

My CSS :first-letter selector is effective on all p elements, however when applied to a span with the id #fletter, it doesn't seem to work... #fletter span:first-letter { font-weight: 600; font-size: 25px; } <span id="fletter"> The : ...