Switch background image using jQuery

I found similar questions and answers, but I'm afraid I'm still a little lost. I just want a bunch of links that will add a Class to the body to change the background image. I only understand how to use the addClass property on the current element that was clicked, but I'm not sure how to get this to add the class to another div. Thanks for any pointers.

+2


source to share


4 answers


Inside the click event of an element, you can use any selector to control the DOM. In this case, I am binding the click event to all anchors on the page. When any anchor is clicked, I add the class to the body element of the page. Returning false ensures that the browser does not follow the href of the anchor.



$("a").click(function(){
    $("body").addClass("CLASS TO ADD");
    return false;
});

      

+4


source


Using addClass ()

$("#your_linkID").click(function(){
    $("#other_div").addClass("CLASS TO ADD");
});

      



or using the css () function

$("#selector_link").click( function(){
    $("#target_div").css({ 'background-image': 'url(/url-to-image.jpg)'});
});

      

+3


source


You can do it like this:

$ ("DIV") addClass ("yourclassname") ;.

+1


source


You can call the method addClass

on any jQuery object.

Therefore, you can use the method $

to create a new jQuery object inside your event handler, for example:

$("a.bd1").click(function(e) {
    $("body").addClass("class1");
    return false;
});

      

For more information on how to select different elements using jQuery read the documentation .

Note that it addClass

accepts a class name, not a CSS selector, so you must add .

to its parameter.

+1


source







All Articles