Is it possible to concatenate a CSS background URL using jQuery?

I am currently using a background for several divs, each with a number from 01 to 10. The current code is as follows:

background: url('assets/bg_01.jpg');

Now, I am looking to change the URL in jQuery when a button is clicked to display bg_01_active.jpg, and so on. Is it feasible to append a variable to the URL, or would I need to manually set it for each individual div?

Answer №1

<div class="asset_images" id="bg_02" style="background-image:  url('assets/bg_02.jpg');">Example</div>

$(".asset_images").click(function() {    
    $(this).css("background", "url('assets/" + $(this).attr('id')  + "_active.jpg'");
});

There are 10 divs with the same class, each with unique ids based on their numbering. The JQuery script will alter the background image URL of each button when clicked according to their specific ids.

Answer №2

If you're looking to update the background url of a button upon clicking it, you can achieve this by following these steps:

<div class='custom-class', id='unique-id'> </div>
$('.custom-class' //or '#unique-id').on('click', function() {
$(this).css('background-image', 'url(new-background)');
});

https://jsfiddle.net/exampleuser/abc123def456/

Answer №3

Why go through the manual labor when programming can do it for you?

 let background = "url('assets/bg_01.jpg')".split(".");
 $(element).css('background-image', background[0] + "_active." + background[1]);

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

Searching for a more sophisticated approach to articulating this concept

I'm facing an issue with a table in my code that has the following structure: ​<table id="mytable"> <tbody> <tr id="tempRowID"> <td class="delete"> <img src="myImage.png" /> </td> < ...

Adjusting the alignment of button text in an Angular Kendo grid

I am currently utilizing the grid view feature of Kendo UI for Angular. While I have buttons on the grid, the issue is that the text within the buttons is not centered properly despite applying styles such as text-align:center. Here is the template for my ...

What is the best way to synchronize the checking and unchecking of two separate checkboxes located in different divs?

I recently implemented two checkboxes to switch between dark mode and light mode. One checkbox pertains to the mobile navigation, while the other one is related to the desktop navigation. When the screen width reaches 800px, the visibility of the checkbox ...

Why does this function execute even after clicking only one of the two keys when using jQuery?

Here is the code snippet I am working with: $(document).bind('keydown', 'ctrl+1', function () { alert('You found the hotkey ctrl+1!'); }); However, when I press either the Ctrl or the 1 key, this code triggers. I specific ...

Can data passed to a PHP page using the .load method of AJAX only be accessed using the $_REQUEST method?

Instead of using $_REQUEST, can data be treated to a PHP page with either $_POST or $_GET? ...

An error has occurred with JSONP due to a lack of the 'Access-Control-Allow-Origin' header in the cross-origin request

Currently, I am utilizing Ajax to retrieve data from Twitter through their API. In attempting to employ jsonp, it seems like I have everything set up correctly (or so I thought). <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery. ...

ng-click stops functioning after ng-bind-html is compiled

I am struggling with integrating a directive into my AngularJS project. app.directive("dir", function($compile, $sce){ return{ restrict: "E", link: function(scope, element, attr){ scope.$watch('content',function() ...

Are there any performance implications when using an excessive number of background images in CSS?

My website seems to be running too slowly based on user reports. I suspect that the background images in CSS may be causing the issue. The site uses a custom build system to concatenate and compress all CSS, create CSS sprites automatically, resulting in ...

Triggering an Ajax request after a session times out

Hey everyone, I've been working on implementing a redirection to the login page in case of a session timeout during an AJAX call. Here's what I've accomplished so far: I created an action filter for all actions. public class AuthenticateFi ...

What could be causing the div to be wider than the content inside of it?

I am having an issue creating a webpage with a 20-60-20 flex fill layout. The div in the center, which should occupy 60% of the page, is wider than its content, causing it to appear off-center. https://i.stack.imgur.com/WwCJy.png Here is my home.componen ...

Determine the reversed position of an element in the index

After conducting some research, I have come across some complicated solutions. However, I am wondering if there is a simpler way to reverse the index of an element using jQuery. At the moment, $('.elementClass').index(this); provides me with t ...

Function that can be shared between two separate jQuery files

Let's say I have two separate jQuery files, both containing the same function. I would like to create a common file where I can store this shared function and then import it into other files. For example: first.js file : window.addEventListener(&apo ...

Verify the values in the dropdown menu and then cross-reference them with the user's input

Is there a way to verify if the textfield, newTeamName, is already included in a list of teamnames that are stored within a select box? I seem to be encountering issues with my code - can you point out what might be the problem? Just to note, there are no ...

Each div will display the same image twice when loading the image

I have a grid where images are dynamically loaded with a link to a lightbox. Currently, this is how I am achieving it: $(".selection_thumb").each( function(i) { $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+(++ ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Bootstrap: one row inside a column with a large width in another row

Hello, I am trying to create a layout with a blue row inside a red col-lg-4 div within a yellow row. Here is the code snippet I have attempted: <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> < ...

Google map with a fully visible HTML element on top

When certain points on a Google map are clicked, a small popup box appears. This works fine in the regular small Google map mode. However, when the Google map is switched to full screen mode by clicking the full screen button (which is shown when `fullScr ...

Which is more powerful: Angular's change detection or directly editing HTML?

One thing I've heard is that Angular's change detection can potentially cause lag in an application when receiving a large amount of data from a websocket. In my setup, the data comes from the socket, updates a variable in the component, and then ...

Having trouble incorporating CSS into a node/express/pug application

I'm currently working on my first Node application using Express and Pug (formerly Jade). Everything seems to be functioning smoothly, except for getting my CSS files to load in the browser. (I keep receiving a "404 Error: GET" when trying to access h ...

Avoid using the table and table-striped classes when working with Bootstrap 5 to ensure a

Recently updated to bootstrap5.0.0-beta3 along with bootstrap-table 1.18.2 from webjars repository. Here's the code snippet: <table id="table">...</table> <!-- no classes here --> $('#table').bootstrapTable({ ...