Reputation: 75
I'm trying to create a function that toggles a div when clicked.
I found an existing Jfiddle that was sort of what I was after and tweaked it.
All is working fine except I need the .search-nav class to be an ID, but when I change it the function stops working.
I've tried various combinations but to no avail.
Working version is here:
http://jsfiddle.net/8rLmokp1/22/
$(function(){
var mglass = $('.magnifying-glass');
var div = $('.search-nav');
mglass.click(function(){
div.toggleClass('drop');
});
});
Version with ID (not working) is here:
http://jsfiddle.net/8rLmokp1/23/
$(function(){
var mglass = $('.magnifying-glass');
var div = $('#search-nav');
mglass.click(function(){
div.toggleClass('drop');
});
});
What am I doing wrong?
Upvotes: 1
Views: 48
Reputation: 167172
That's specificity issue. You need to target using both id
and class
in CSS:
#search-nav.drop {
width: 200px;
height: 100px;
}
You are using height
in both #search-nav
and .drop
. Since .drop
is less specific, it applies the properties of #search-nav
. To increase the specificity, you need to add the the id
selector as well, like #search-nav.drop
.
This would help you understand:
Updated Fiddle: http://jsfiddle.net/npu8vkbo/
Upvotes: 1
Reputation: 337560
The issue is due to the specificity of the drop
CSS class. As you changed the search-nav
element to be styled by its id
the id selector overrides any styles applied by a class. Therefore you need to increase the specificity of the .drop
rules by prepending the id to it. Try this:
#search-nav.drop {
width: 200px;
height: 100px;
}
Upvotes: 1
Reputation: 382112
It's because #someId
has a greater specificity than .someClass
.
From the MDN:
The following list of selector types is by increasing specificity:
Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
ID selectors (e.g., #example).
You may change the selector in the CSS from
.drop
to
#search-nav.drop, .drop
Upvotes: 1