Add class for parent of parent - javascript

how can I add a class in a drop dowwn menu on click when child of parent of parent is clicked.
This is my html:
<ul id="FirstLevel">
<li>FirstLevel</li>
<li>FirstLevel
<ul class="secondLevel">
<li>SecondLevel</li>
<ul class="LastLevel">
<li>LastLevel</li>
<li>LastLevel</li>
</ul>
<li>SecondLevel</li>
<li>SecondLevel</li>
</ul>
</li>
<li>FirstLevel</li>
<li>FirstLevel</li>
<li>FirstLevel</li>
</ul
So what I need is that; onclick on LastLevel or SecondLevel of my menu I want to add a class via jQuery on FirstLevel li and to remove that class when another sub menu is selected.
I've tried this but is not really working:
$('#firstUl').find('li').click(function(){ //removing the previous selected menu state $('#firstUl').find('li').removeClass('active'); //is this element from the second level menu? if($(this).closest('ul').hasClass('lastLevel')){ $(this).parents('li').parents('li').addClass('menuActive'); //this is a parent element }else{ $(this).addClass('menuActive'); } });
Thank you.

Give your FirstLevel <li>'s a class, it'd make it much easier to target the correct element:
<li class="first-level">FirstLevel</li>
Then attach a click handler to all child <li>'s:
$('li.first-level li').on('click', function(e) {
e.preventDefault(); // prevent the link from being followed
$(this).closest('li.first-level').toggleClass('yourClass') //
.siblings('li.first-level').removeClass('yourClass');
});
Here's a fiddle

This does all the things you want:
$("ul.secondLevel a").click(function () {
$("#FirstLevel>li").removeClass("blue");
$(this).parents("ul.secondLevel").parent().addClass("blue");
});
Check here: http://jsfiddle.net/c4dTK/

Here is the solution :
$('.secondLevel li a').click(function (e) {
$('#FirstLevel > li').removeClass('selected');
$(this).parents('.secondLevel').parent().addClass('selected');
})

As your first level list has been given an Id, you could just find the element using a selector as follows:
$(".secondLevel a").click(function () {
e.preventDefault();
$("#FirstLevel li").addClass("newClass");
});

try this
jQuery(this).parent('ul').addClass('yourClass');
Or:
jQuery(this).parents('ul').addClass('yourClass');

here goes another answer
var test= $('li li,li li li')
console.log(test)
test.click(function(){
$(this).parents('ul').closest('li').addClass('kaka');
});
jsfiddle

Related

jQuery: When parent element is clicked, hide child element. When child element is clicked, don't hide it

I have a parent element with a child element that is displayed/hidden by clicking a specific button on the page. The button just changes the style from display:none to display:block, pretty simple. The child element starts off as display:none;
I want to hide this element when the parent element is clicked, but not when the child element is clicked, which is problematic since the child element is apart of the parent element.
I saw that there was data(); that can check if an element was clicked, but that doesn't seem to be working.
Here is the html:
<style>
#parent {width:200px;height:200px;}
#child {display:none;width:50px;height:50px;}
#child.display {display:block;}
</style>
<div id="parent">
Some content
<div id="child">Some other content</div>
</div>
<button id="clickMe">Toggle Child</button>
And here is the jQuery:
$(function()
{
$('#clickMe').click(function()
{
$('#child').toggleClass('display');
});
$('#parent').click(function()
{
if($('#child').data('clicked') == true )
{
// do nothing
} else
{
$('#child').toggleClass('display');
}
});
});
For the sake of this example I hid the child element by default. Don't worry, I won't be doing that in production. I'm just working on figuring out how to do this base functionality.
Here is a link to demo of it: jsfiddle
You can accomplish that by binding an event to the child and stop the propagation.
$('#parent').click(function() {
$('#child').toggleClass('display');
});
$('#child').click(function(e) {
e.stopPropagation();
});
More information can be found here
Updated Fiddle
Here's an updated fiddle with the problem resolved: https://jsfiddle.net/6u39dfxd/1/
$('#clickMe').click(function() {
$('#child').toggleClass('display');
});
$('#parent').click(function(event) {
if($(this).has(event.target).length === 0) {
$('#child').toggleClass('display');
}
});
Basically, you get the event.target on click and ensure that it's not contained within the parent element. You could get more specific if there's more than one child, but this should resolve it.
$('#clickMe').click(function()
{
$('#child').toggle();
});
$('#parent').click(function(e)
{
$('#child').toggle();
});
$("#parent").children().click( function(e) {
e.stopPropagation();
});
I think this will solve your problem.

Li parent elemnt is not selected on child li selection in jquery

I have write code to make the li active on url basis .It works fine but it fails on child li.It make child li active while i want that top li should be active not child.My code is below:
<script type="text/javascript">
jQuery(function () {
setNavigation();
});
function setNavigation() {
// this portion code make li active on url basis
var pathname = window.location.pathname;
path = pathname.replace(/\/$/, "");
path = decodeURIComponent(path);
var value = jQuery(location).attr('href');
// value = value.replace('.html', ''); alert(value);
jQuery(".flexy-menu a").each(function () {
var href = jQuery(this).attr('href');
if (value === href) {
jQuery(this).closest('li').addClass('active');
}
});
// this is code for child li but only first code works
jQuery('.flexy-menu').children('li').click(function(){
jQuery(this).parent('li').addClass('active');
});
}</script>
My HTML is like this :
<ul class="flexy-menu orange">
<li style="">Home</li>
<li style="">Collection
<ul style=""> <li>My Secret Garden </li>
<li>Legend</li></ul>
</li>
<li class="active" style="">Artisans</li>
<li style="">Contact </li>
</ul>
Instead of parent use .closest():
jQuery(this).closest('li').addClass('active');
and put this in doc ready:
jQuery(function () {
setNavigation();
jQuery('.flexy-menu').find('li').click(function(){
jQuery(this).closest('li').addClass('active');
});
});
Here i changed your selector little bit with .find() instead of .children(), because .find() looks for grand child also and if you want to traverse up to the parent then use .closest() method.
I have write code to make the li active on url basis
Okay! then you can choose to do this:
$('a[href*="'+ path +'"]').parents('li').addClass('active');
This should work:
All to all you just need to do this only, no extra function required:
jQuery(function () {
var path = window.location.pathname;
$('a[href*="'+ path +'"]').parents('li').addClass('active');
jQuery('.flexy-menu').find('li').click(function(){
jQuery(this).closest('li').addClass('active');
});
});
jQuery('.flexy-menu > li').click(function(e){
jQuery(this).closest('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
Demo:
http://jsfiddle.net/hqPQu/

Check if button clicked has ID that starts with a particular String in jQuery

I am using Twitter Bootstrap and have the following code
<div class="btn-group">
<a id="id_btn_dropdown_policies" class="btn dropdown-toggle" data-toggle="dropdown" href="#">
--Select-- </a>
<ul class="dropdown-menu">
<li>policy1</li>
<li>policy2</li>
<li>policy3</li>
<li>policy4</li>
</ul>
</div>
and my function is
$(function() {
$(".dropdown-menu li a").click(function() {
//check if button clicked is of id that starts with id_btn_dropdown_policy
$("#id_btn_dropdown_policies").text($(this).text());
$("#id_btn_dropdown_policies").val($(this).text());
getCategory($(this));
});
});
I want setting the text and value of element with id id_btn_dropdown_policies only if this.id.indexof("id_btn_dropdown_policies")=0
I am not able to do this in jQuery because looks like there is no indexof method. I tried
if($(this).attr('id').indexof("id_btn_dropdown_policy") == 0) {
alert("Matched");
};
which is not correct. So what is the correct way?
There is no indexof method indeed, it's indexOf (capital 'O') you're looking for.
See MDN
You may try following handler instead (Register your handler only for those a tags whose id begins with id_btn_dropdown_policy):
$(".dropdown-menu li a[id^='id_btn_dropdown_policy']").click(function() {
// code goes here
});
In this case, a[id^='id_btn_dropdown_policy'] means that, all a tags whose id begins with id_btn_dropdown_policy. So clicking on other a tags won't take any action.
$(".dropdown-menu li a[id^='id_btn_dropdown_policy']")
is a crapy selector you should use indexOf method of javascript.
i.e
if($(this).attr('id').indexOf("id_btn_dropdown_policy") == 0) {
alert("Matched");
};
My suggestion will be use common class for those div and then select by classs selector.
I'm not positive I understand your question, but you can use the "attribute starts with" selector in jQuery to make your selections.
$(function () {
$(".dropdown-menu li a").click(function () {
//check if button clicked is of id that starts with id_btn_dropdown_policy
$( "[id^='id_btn_dropdown_policies']" ).text($(this).text());
$( "[id^='id_btn_dropdown_policies']" ).val($(this).text());
getCategory($(this));
});
});

Select all elements except a certain class

I'm trying to hide .menu_branch using jQuery slideUp() only if the user clicks off of .menu_root. I'm not getting any errors but the click() function is executing even if .menu_root is clicked. Any ideas? jQuery or straight JavaScript are both fine by me. Thanks!
HTML:
<span class="menu_root">Menu</span>
<ul class="menu_branch">
<li>Home</li>
<li>FAQ</li>
<li>About</li>
<li>Contact</li>
</ul>
CSS:
.menu_branch {
display:block;
}
Jquery:
$("body:not(.menu_root)").click(function(){
$(".menu_branch").slideUp("fast");
});
I've also tried:
$("body").not(".menu_root").click(function(){
$(".menu_branch").slideUp("fast");
});
As well as replacing body with * in both instances, all with the same result.
One possible solution is to prevent the propagation of click event from menu_root
$(document).click(function () {
$(".menu_branch").slideUp("fast");
});
$('.menu_root').click(function (e) {
e.stopPropagation();
})
Demo: Fiddle
Your code will ignore a body element with class menu_root like <body class="menu_root">
You can try this:
$("body").click(function(event){
if ( $(event.target).hasClass("menu_root") ) {
return false;
}
$(".menu_branch").slideUp("fast");
});
http://jsfiddle.net/WzW2D/2/
Late to the party again but this should work for you. Clicking .menu_root will toggle the menu. Clicking anywhere else will close it (if its open).
$(document).on("click", function(e) {//When the user click on any element:
if($(".menu_branch").is(":visible")){//If the menu is open...
$(".menu_branch").slideUp("fast");//close it.
} else if ($(e.target).hasClass("menu_root")){//Otherwise, if the user clicked menu_root...
$(".menu_branch").slideDown("fast");//open it.
}
});
http://jsfiddle.net/xGfTq/
try
$(document).click(function () {
$(".menu_branch").slideUp("fast");
});
$('.menu_root').click(function () {
return false;
})

adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.
HTML:
<div id="mainNav">
<ul id="nav">
<a id="mainLogo" href="/"><li></li></a>
<a id="aboutLink" class="aLink" href="/"><li></li></a>
<a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
<a id="external" href="/"><li></li></a>
</ul>
</div><!--/#mainNav-->
I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.
jQuery:
$(function () {
$(".aLink").click(function () {
if ($(this) == $("#aboutLink")
$(this).addClass('activeLink');
else $(this).addClass('active2Link');
});
});
Thanks for any input or direction.
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(){
e.preventDefault();
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
You could, instead, use toggleClass() to allow for those classes to be removed by a second click:
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(e){
e.preventDefault();
$(this).toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
Edited in response to question, from the OP, in comments, below:
How would I remove the class so that both links don't appear to be active at the same time?
There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:
$('#nav a').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('ul').find('a[class]').attr('class', '');
self.toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:
$('#nav a').click(function(e){
e.preventDefault();
for (var id in idToClass) {
if (idToClass.hasOwnProperty(id)){
$('#' + id).removeClass(idToClass[id]);
}
}
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
If, of course, you use a common class-name then it all becomes much easier:
$('#nav a').click(function (e) {
e.preventDefault();
var self = $(this);
self.closest('ul')
.find('.commonActiveClassName')
.removeClass('commonActiveClassName');
self.addClass('commonActiveClassName');
});
JS Fiddle demo.
References:
addClass().
closest().
event.preventDefault().
find().
removeClass().
toggleClass().
Since you already have ID tags to easily reference... I think you want something more like this?
$(function () {
$("#aboutLink").click(function () {
$(this).addClass('activeLink');
});
$("#sasLink").click(function () {
$(this).addClass('active2Link');
});
});
Try using this instead:
$(function () {
$(".aLink").click(function () {
var currentId = this.id;
if ( currentId == "aboutLink"){
$(this).addClass('activeLink');
else if( currentId == "sasLink") {
$(this).addClass('active2Link');
}
});
});

Categories

Resources