tags:

views:

327

answers:

5

I have found similar questions and answers but afraid I am still a bit lost. I just want a set of links that will addClass to the body to change the background image. I only understand how to use the addClass property on the actual element being clicked, but I am not sure how to get that to add a class to another div. Thanks for any pointers.

+3  A: 

Inside the click event of the element, you can use any selector to manipulate the DOM. In this case, I am attaching a click event to all the anchors on the page. When any anchor is clicked, I am adding a class to the body element of the page. The return false makes sure that the browser does not follow the href of the anchor.

$("a").click(function(){
    $("body").addClass("CLASS TO ADD");
    return false;
});
T B
Thanks for the response.. that seems like it should work but no go for me.. perhaps it is how I am using my CSS?body {margin:0px;}.class1{background: url(../images/sprays.jpg) repeat;} $("a.bd1").click(function(){ $("body").addClass(".class1"); return false;<a class="bd1" href="#"><img src="images/box.gif"></a>
zac
`addClass` takes a class name, not a CSS selector. Remove the `.` from the call to `addClass` and it should work fine.
SLaks
SLaks is right, you should use $("body").addClass("class1") without the period since it doesn't take a selector
T B
+1  A: 

You can do it like this:

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

Jaxwood
+2  A: 

Using addClass()

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

or using css() function

$("#selector_link").click( function(){
    $("#target_div").css({ 'background-image': 'url(/url-to-image.jpg)'});
});
Elzo Valugi
The syntax of your css call is incorrect. Either put backgroud-image in quotes or change it to backgroundImage. Also, the url of the image needs to be wrapped with url() like "url('/url-to-image.jpg')"
T B
thanks. It was a fast response.
Elzo Valugi
+1  A: 

You can call the addClass method on any jQuery object.

Therefore, you can use the $ method to create a new jQuery object inside your event handler, like this:

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

For more information about how to select various elements using jQuery, read the documentation.

Note that addClass takes a class name, not a CSS selector, so you should add a . to its parameter.

SLaks
great thanks.. i was adding a class like ".class1" rather than "class1" was my problem
zac
A: 

Just wanted to add that I also had to add a $("body").removeClass(); to make this work right

zac