Reputation: 446
I cannot get working jQuery toggleClass() within if-else condition.
My HTML code is:
<ul>
<li class="firstLevel">
<a href="#main_cat_01">MAIN CATEGORY #1</a>
<ul class="dijete">
<li>
<a href="#subt_cat_01">SUB CATEGORY #1</a>
</li>
</ul>
</li>
<li class="firstLevel">
<a href="#main_cat_02">MAIN CATEGORY #2</a>
<ul class="dijete">
<li>
<a href="#subt_cat_02_01">SUB CATEGORY #1</a>
</li>
</ul>
</li>
</ul>
My CSS code is:
ul.dijete {
display: none;
}
.vidimte{
display: block;
}
My JavaScript code is:
var $j = jQuery.noConflict();
$j(function() {
$j('li.firstLevel').click(function(){
if($j(this).children("ul.dijete").hasClass("vidimte")){
$j(this).children("ul.dijete").toggleClass('vidimte'); //visible
$j(this).find("ul.dijete").prev("li.firstLevel a").css({
"background-image":'url(URL_TO_THE_IMAGE_OPEN)',
"background-position":"right center",
"display":"block",
"background-repeat":"no-repeat"
});
}else{ // else add image close and display none
$j(this).find('ul.vidimte').prev("li.firstLevel a").css({
"background-image":'url(URL_TO_THE_IMAGE_CLOSE)',
"background-position":"right center",
"display":"block",
"background-repeat":"no-repeat"
});
}
});
});
I cannot get this working.
Do I have to use on.('click) method for that?
Any ideas?
Thanks for help or any information!
Upvotes: 3
Views: 468
Reputation: 73
the .toggleClass()
function is used to remove or add classs, that is said in your question in your else
expression you didn't remove or add the class back;
add $j(this).children(".dijete").toggleClass('vidimte')
to else
but I think your goal is that click the link then show/hide the sub link also change background. then codes link these:
$j(this).children('ul').toggleClass('dijete vidimte')
Upvotes: 1
Reputation: 446
Got it! Thanks for sharing ideas!
Solution worked for me:
var $j = jQuery.noConflict();
$j(function() {
$j('li.firstLevel').on('click', function() {
if($j(this).closest("li").children("ul.dijete").length){
$j(this).children("ul.dijete").toggleClass('vidimte');
if($j(this).children("ul.dijete").hasClass("vidimte")){
$j(this).find("ul.dijete").prev("li.firstLevel a").css({
"background-image":'url(http://www.v-tac.hr/wp-content/themes/vtac/images/stories/customfilters/open.png)',
"background-position":"right center",
"display":"block",
"background-repeat":"no-repeat"
});
}else{
$j(this).find('ul.dijete').prev("li.firstLevel a").css({
"background-image":'url(http://www.v-tac.hr/wp-content/themes/vtac/images/stories/customfilters/closed.png)',
"background-position":"right center",
"display":"block",
"background-repeat":"no-repeat"
});
}
}
});
});
Upvotes: 1