Reputation: 3
I'm trying to wrote my script for onepageweb nav. Main goal was to change selector on click and first part is working fine but first li is site logo so when I click on logo I want add .select
second li. :
$(document).ready(function (){
$(".main-nav li").click(function () {
if (this = $(".main-nav li:first-of-type")) {
$(this).next().addClass("selected")
.siblings().removeClass("selected");
} else {
$(this).addClass("selected")
.siblings().removeClass("selected");
}
});
});
and this condition not work
Upvotes: 0
Views: 61
Reputation: 1074148
Two problems:
You're using =
for comparison (if (this = $(".main-nav li:first-of-type"))
). =
is always assignment. Since you can't assign to this
, that's an error and nothing else will happen.
If you were using ==
or ===
there, it wouldn't work, because this
will refer to a DOM element, but the return value of $()
is always a jQuery object.
You may want
if ($(this).is(".main-nav li:first-of-type"))
...which uses is
to test if the clicked element matches the given selector.
Side note: :first-of-type
should work, but because ul
elements can only contain li
elements, :first
would work as well.
Live Example:
$(document).ready(function() {
$(".main-nav li").click(function() {
if ($(this).is(".main-nav li:first-of-type")) {
$(this).next().addClass("selected")
.siblings().removeClass("selected");
} else {
$(this).addClass("selected")
.siblings().removeClass("selected");
}
});
});
.selected {
color: red;
}
<ul class="main-nav">
<li>The logo item</li>
<li>The second item</li>
<li>The third item</li>
<ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 3