Reputation: 1321
Simply want to change the background dynamically, don't seem to be able to do it, what am I missing here? I should clarify, that it is the background of the container div I am trying to change...
$('#container').click(function(){
$(this).toggleClass('bgchange');
});
$('#container ul li').click(function(){
$(this).toggleClass('bgchange');
});
Fiddle http://jsfiddle.net/7ed7zs9w/1/
Upvotes: 0
Views: 21
Reputation: 15112
JSFIDDLE DEMO -> http://jsfiddle.net/7ed7zs9w/4/
This is happening because you have background-color mentioned in the #container
selector in the CSS which has the higher hierarchy than the class bgchange
. Hence it never changes.
Make the following changes:
HTML
<div id="container" class="redbg"> //add class redbg here
CSS
#container{
height: 150px; //remove background-color here
overflow-y: scroll;
}
.bgchange{
background-color: blue;
}
.redbg{
background-color: red;
}
jQuery
$('#container').click(function(){
$(this).toggleClass('redbg bgchange'); // toggle between 2 classes instead of 1
});
$('#container ul li').click(function(e){
e.stopPropagation(); // add this here
$(this).toggleClass('bgchange');
});
Upvotes: 0
Reputation: 4349
The id identifier is more specific than the class identifier for the container css so it gets overridden. Therefore if you want to override for the container and have it also change color add !important
. Example http://jsfiddle.net/e5bgsh3v/
Upvotes: 1