Switching between displaying or hiding one of two backgrounds within a div using CSS and jQuery

Seeking guidance on implementing a two-background div setup where A is constantly displayed within the element and toggling B based on button control click.

HTML

<div class="container"></div>

CSS

.container{
  url(B.png) 10px 10px no-repeat, 
   url(A.png) 600px 10px no-repeat,  
}

JQUERY

$('.container').on('click', function(){

     //$(this).css("background","A.png")? add/removeClass?
  });

Looking for assistance in achieving this implementation.

Answer №1

To create a toggle effect for showing/hiding background images, you can utilize the background-size property:

$('.container').on('click', function() {
  $(this).toggleClass('hide');
});
.container {
  width:400px;
  height:200px;
  background-image: 
  url(https://lorempixel.com/300/200/), 
  url(https://lorempixel.com/350/200/);
  background-size: cover;
  background-repeat: no-repeat;
}

.hide {
  background-size: 0 0, cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

Answer №2

It seems like you want to display one image as the default background and then toggle it with another image.

Here is my suggestion:

  1. Create a new CSS class called extra-background, place Image A in the .container, and Image B in the .extra-background class.

  2. On click, use toggleClass('extra-background')

$('.container').on('click', function(){
   $(this).toggleClass("extra-background");
});
.container{
 background: url("https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Vue.png/215px-Vue.png") #00D no-repeat fixed;
  width:400px;
  height:400px;
}

.extra-background{
 background: url("https://upload.wikimedia.org/wikipedia/en/thumb/c/c9/VueCinemas.svg/1200px-VueCinemas.svg.png") #00D no-repeat fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">Test</div>

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

Quick tip: Automatically expand the thumbnail wrapper in an image gallery upon page load using jQuery

As someone who is new to jquery and still learning, I wanted to share a beautiful gallery that uses jquery on my website. You can find the link to it here: http://tympanus.net/Tutorials/ThumbnailsNavigationGallery/ The gallery has a snippet that allows u ...

The <a> tag does not have the clickability feature

My personal website doesn't allow me to click on the links that I have added for web pages. Here is the CSS code I am using: @font-face { font-family: typewrite; src: url(fonts/typewcond_regular.otf); } @font-face { font-family: typewrite; sr ...

Modifying .vue files within Laravel seems to unexpectedly impact unrelated CSS styles

I've been working on a Laravel project that involves building Vue components. Strangely, every time I update a .vue file and add it for a commit, modifications are also made to the app.css and app.js files. These changes seem to be undoing a particula ...

Altering the color of a div based on a specified value condition

I am in need of assistance with a div structure similar to this: <div id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable ></div> <div id="position" tabindex="1" class="filled-text" placeholder="Input ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

Tips for streamlining the use of hidden and visible div elements with concise code

I have been attempting to use the same code for multiple modules on this page, but none of the methods I've tried seem to be effective. I want to avoid endlessly duplicating existing code. document.addEventListener('DOMContentLoaded', fun ...

Why does the DropDownList consistently remove the initial value?

I am currently in the process of developing a recipe website focused on meals. I have created an admin panel where I can manage the meals added to the site. One issue I am facing is with deleting a meal that was previously added. The menu displays the numb ...

Encountering a parser error during an Ajax request

Attempting to develop a login system with PHP, jQuery, Ajax, and JSON. It successfully validates empty fields, but upon form submission, the Ajax call fails. The response text displays a JSON array in the console, indicating that the PHP part is not the is ...

Preserve the content in the text box corresponding to the selected radio button

In my form, there are multiple radio buttons, each with an associated text box value. Users can only select one radio button at a time and submit the form. However, sometimes users will enter data in a textbox for one radio button, then switch to another o ...

What could be causing the modal to not appear when clicking on this div?

$(function() { $("#pagination a").trigger('click'); // When the page loads, trigger a click event $('body').on('click','div.well well-sm',function(){ var list = $(this); $('#myModal .modal-title').h ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

The Unexpected Mishaps of CSS Grid Layout

I attempted to create a grid using CSS, but I seem to have made an error somewhere in my code. Can someone please take a look at my jsFiddle link and provide some guidance? jsFiddle /*Grid*/ .container { width: 100%; max-width: 1200px; } .row:before, ...

Getting the most out of your weather API: optimizing search parameters for precise location results and avoiding any confusion with similar locations

When experimenting with new platforms, I often utilize the openweathermap.org's api. However, I have encountered a recurring issue where I struggle to define a precise query for finding certain cities. The api functions smoothly for major cities like ...

Looking to effectively personalize various React MUI components?

I want to enhance the MUI component by adding more variations and new properties. Check out this screenshot of a React Example component: The Example component can be seen in the image above. I am seeking advice as I don't have much experience with ...

Struggling to forward JSON data via AJAX to Django without relying on jQuery

My goal is to utilize AJAX in conjunction with Django, but I want to achieve this without relying on jQuery. So far, I have made progress in sending URL encoded data from AJAX to Django successfully. However, I am currently facing an issue where I am unabl ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

What are the steps to incorporate fading effects into a jQuery popup box?

Currently, I have implemented a jQuery function to display a popup box using .show() and hide it using .hide(). Is there a way to incorporate charming animations such as fading into the popup box? // display pop up $('.mypopup').show(); // con ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

What is the best way to place a child on top of a different parent in the stack?

There is a collection of figure tags, each with an expandable figcaption. Inside each figure, there is a clickable div that reveals the figcaption when clicked. However, the visible figcaption only overlaps the figure it belongs to and not others. Is there ...