i wonder why this onclick work on this div:
<div id="block-block-contact" class="block-factice expanded" onclick="sessionStorage.contactclass=this.className ">
but not on this li
<li id="dhtml_menu-1895" class="first collapsed dhtml-menu collapsed start-collapsed menu-1895" onclick="sessionStorage.menu1895=this.className">
meaning when i click on the div, it does store the contactclass variable whereas when i click on the li, it does not store the menu1895 variable
Matoeil,
Can you please check this
https://jsfiddle.net/612ee2df/
<ul>
<li id="dhtml_menu-1895" class="first collapsed dhtml-menu collapsed start-collapsed menu-1895" onclick="sessionStorage.menu1895=this.className">
Test
</li>
</ul>
jQuery
$(document).ready(function(e)
{
$('ul li').on('click',function(e)
{
var cls = $(this).attr('class');
alert(cls);
sessionStorage.menu1895 = cls;
})
})
Because I tried your code-snippet but instead of JavaScript I used jQuery & it saved the value in session storage.
another event was linked to this element.
To strip all event listeners i did
var old_element=document.getElementById("dhtml_menu-1895");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
and now it works
Related
I have a page with a list of menu items consisting of internal anchors. I'm trying to add an .active class to the selected item. It seems to work on load but when clicking a new item in that same page it doesn't.
When clicking a new menu item, I would like to remove all other active classes and add this class to the clicked item.
Sounds pretty simple, but I can't make it work.
I created this Fiddle, but it doesn't show the issue correctly, since I can't add hashes to the url.
However, maybe someone can point me in the right direction.
JS:
function setActiveLinks() {
var current = location.pathname;
$('.bs-docs-sidenav li a').each(function() {
var $this = $(this);
// Get hash value
var $hash = location.href.substr(location.href.indexOf('#') + 1);
if ($this.attr('href') == '#' + $hash) {
$this.parent().addClass('active');
}
})
}
setActiveLinks();
$('#leftmenu li a').click(function() {
$('#leftmenu li').removeClass('active');
setActiveLinks();
});
HTML:
<ul class="nav bs-docs-sidenav">
<li>
Download
</li>
<li class="active">
What's included
<ul class="nav">
<li class="active">Precompiled</li>
<li>Source code</li>
</ul>
</li>
<li>
Compiling CSS and JavaScript
<ul class="nav">
<li>Installing Grunt</li>
<li>Available Grunt commands</li>
<li>Troubleshooting</li>
</ul>
</li>
</ul>
Thanks. :-)
You have wrong selector to bind click event on anchor element. also you don't need to call setActiveLinks() function(which sets class based on href) here.
You can use context of clicked anchor element to traverse to parent li and add class active in it:
var $navLIs = $('.nav li')
$navLIs.find('a').click(function() {
$navLIs.removeClass('active');
$(this).parent().addClass('active');
});
Working Demo
I have been trying to create a variable and then insert it into Child Selector using jQuery i.e. $("parent > child") with no luck.
I have included the entire applicable segment of jQuery code as reference, the overall idea is that when a navigation button is clicked, the class ".is-checked" is added to the navigation button ".nav-collapse". Each button is associated with a unique data-filter that is applied via jQuery Isotope.
The issue I am having is that later on in the code, I am then trying to correctly call out the associated checked navigation button's data-filter (using the var = sclass) and apply this as a selector via the Child Selector $("parent > child") but have been having trouble getting this to work.
Issue is with the last 2 lines of code:
$('.nav-collapse').on( 'click', 'button', function( event ) {
var $target = $( event.currentTarget );
$target.toggleClass('is-checked');
var isChecked = $target.hasClass('is-checked');
var filter = $target.attr('data-filter');
if ( isChecked ) {
addFilter( filter );
} else {
removeFilter( filter );
}
$grid.isotope({ filter: filters.join(',') });
$(".masonry-image a").click(function(){
var sclass = $('.nav-collapse.is-checked').children().attr('data-filter');
$(" li." + sclass + " > a[href$='-hi.jpg']").addClass("fancybox-button")
...
However, if I change the selector "parent" to an existing selector li class="li class1", for example:
$(" li.class1 > a[href$='-hi.jpg']")
then the functionality I am going for works effectively, so I know I am on the right track. I have not been able to find any examples of creating a variable then inserting it as the parent within the selector, so I am not sure if my issue lies within how I have set up the selector, or how I have constructed the variable, or both.
<nav class="nav-collapse">
<ul>
<li><button class="button" data-filter=".class1">Class 1</button></li>
<li><button class="button" data-filter=".class2">Class 2</button></li>
<li><button class="button" data-filter=".class3">Class 3</button></li>
</ul>
</nav>
<li class="masonry-image class1">
<a href="images/shared/00001-hi.jpg">
<img src="images/shared/00001.jpg" width="308" height="205" alt=""/>
</a>
</li>
<li class="masonry-image class2">
<a href="images/shared/00002-hi.jpg">
<img src="images/shared/00002.jpg" width="308" height="205" alt=""/>
</a>
</li>
Did you even check your sclass? Console.log is your friend ;)
As .children only travels down 1 level it will only check the UL. It will never reach the button.
Try:
var sclass = $('.nav-collapse.is-checked').find("button").attr('data-filter');
Or:
var sclass = $('.nav-collapse.is-checked button').attr('data-filter');
EDIT: oops I misinterpreted your code, I think you need:
var sclass = $('.nav-collapse').find('.is-checked').attr('data-filter');
Or this (note the space!):
var sclass = $('.nav-collapse .is-checked').attr('data-filter');
For your last line of code remove the dot after the li, or remove the dots from the data-filters.
I have this code http://jsfiddle.net/cwahL1tz/
My HTML
<ul class="myFilters">
<li data-type="A">A</li>
<li data-type="B">B</li>
<li data-type="C">C</li>
</ul>
<div class="filter">
<ul class="title">
<li>Assurance</li>
<li>Couverture</li>
<li>Banque</li>
<li>Alimentation</li>
</ul>
<div id="Assurance" class="category">
<ul>
<li>Groupama</li>
</ul>
</div>
<div id="Couverture" class="category">
<ul>
<li>Try it !</li>
</ul>
</div>
<div id="Alimentation" class="category">
<ul>
<li>AN example</li>
</ul>
</div>
</div>
Here's my JS script
jQuery(function ($) {
$('.myFilters li').click(function(){
$(".category").hide();
var v = $(this).text()[0]
$('.title li').hide().filter(function(){
return $(this).text().toUpperCase()[0] == v;
$(".category:first").show();
}).show()
})
$("a[data-toggle]").on("click", function(e) {
e.preventDefault(); // prevent navigating
var selector = $(this).data("toggle"); // get corresponding element
$(".category").hide();
$(selector).show();
});
});
It works fine but I trying to arrange some stuff but I'm stuck.
When I load the page all the links and divs appears, I just only want the divs of the first letter appear.
And when I click on C for example, I want the first div to show from the first link.
Thanks for your help !
EDITED:
On load:
$('.myFilters li:first').trigger('click');
And inside its click:
.first().find('a[data-toggle]:first').trigger('click');
jsfiddle DEMO
You can simply do that with first selecting the element with the right selector and then you can trigger the click event manually :
Show the Assurance content on load :
$('a[data-toggle="#Assurance"]').click();
Show first content on click :
$('.myFilters li').click(function(){
$(".category").hide();
var v = $(this).text()[0]
$('.title li').hide().filter(function(){
return $(this).text().toUpperCase()[0] == v;
}).show()
$('a[data-toggle]:visible:first').click();
})
Updated jsFiddle
Without going into any more javascript, you can display the content the way you would like using css selectors:
.category {display:none;}
.category:nth-of-type(1) {
display:block;
}
http://jsfiddle.net/5ageasm4/1/
Is this what you want. Check the Fiddle
I am basically just triggering the first item in the li
$(".title > li:first").find("a[data-toggle]").trigger("click");
and i am doing the same with the category.
EDIT
I updated my Fiddle
NEW EDIT
Created a new Fiddle, this one just removes all the duplicate code.
So basically i created these 2 functions
that.selectFirstElem = function(selector){
selector.find("a[data-toggle]").trigger("click");
};
that.loadFirstDataToggle = function(input){
return $('.title li').hide().filter(function(){
return $(this).text().toUpperCase()[0] == input;
}).show();
};
And those 2 functions you can just call in the places where you need it.
I'm new to javascript and I wanted to create an event onclick to list items. The problem is that I want to create an event to the li tag, but it keeps firing when I click the descendent ul's.
Here goes part of my code:
<li id="1660761" class="HTMLFirstLevel HTMLHorizontalArrowDown">
<ul id="ul1223945" class="HTMLItem">
<li id="1490659" class="HTMLRemainingLevels"></li>
<li id="483463" class="HTMLRemainingLevels"></li>
<li id="80919" class="HTMLRemainingLevels"></li>
<li id="1280053" class="HTMLRemainingLevels"></li>
<li id="1799353" class="HTMLRemainingLevels"></li>
<li id="1882209" class="HTMLRemainingLevels"></li>
<li id="462917" class="HTMLRemainingLevels"></li>
</ul>
</li>
<li id= ......>
<ul....>
<ul...>
</li>
and my javascript:
var parentNode = document.getElementById('1660761');
parentNode.addEventListener("click",function(e) {
alert('Hi There');
});
}
Now I only want it to fire on the item li with the id 1660761, and not the items inside the list.
The list is an imported component and I can't create events inside the html, that's why I'm accessing it outside with javascript.
Now here's how I've done it by scaning the div by tag name and then adding a "click" event listener if the content equals the tag inner html that I was searching for.
I leave the rest of the html that it's important to this aproach:
<div id="MainMenu" class="HTMLMenuContainer HTMLMenuHorizontal">
<ul id="ul1351387" class="HTMLMenu">
<li id="1660761" class="HTMLFirstLevel HTMLHorizontalArrowDown">
<a href="#">
<span>Back Office</span>
</a>
<ul id="ul1172716" class="HTMLItem">
<li id="1490659" class="HTMLRemainingLevels">
<a href="#">
<span>
Some submenu Here
</span>
</a>
</li>
.....
and the code:
var divs = document.getElementsByClassName('HTMLMenuHorizontal');
var span = divs[0].getElementsByTagName('span');
//I iterate till 19 cause its more than all the spans in the page.
for(var i=0; i<20; i++) {
var sp= span[i];
if(sp.innerHTML==('Back Office')){
sp.addEventListener("click",function back(){
//do something here like
alert('Back Office');
});
}
}
This works fine and it doesn't fire on the itens inside.
This works because in my case the itens doesn't change the content, only the visibility.
I do the same for all the other itens that have descendents.
Thank you all.
Below is my jQuery code for this problem:
$(function(){
$("li.1660761").live("click", onListItemLink);
}
function onListItemLink(){
alert('Hello World!');
}
This one is for JavaScript:
var parentNode = document.getElementById('1660761');
parentNode.onclick = onListItemLink;
function onListItemLink(){
alert('Hello World!');
}
take a look at this page to undersand correctly:
capture event
and what's function(e-->??)
I hope it helps.
$('#1660761').unbind('click').click(function(e) {
if (e.target !== this) return;
alert('Hey There!');
});
Try This code : http://jsfiddle.net/sd5LZ/
I have a HTML markup that looks like
<ul>
...
<li>
<ul class="x">
...
<a href="#"...
How can I get the parent ul.x element from a click event hooked on the link?
this.parentNode works if the UL is the parent element, but if it's one of the ancestors I have to use this.parentNode.parentNode depending on how many parent elements are in between...
Can I somehow get the first UL parent?
Since you've tagged the question as jQuery:
$(this).closest("ul"); //Get the first ancestor `ul`
$(this).closest("ul.x"); //Get the first ancestor `ul` with class `x`
Or, without jQuery (since your example doesn't seem to be using jQuery):
var node = this;
while(node.tagName !== "UL") {
node = node.parentNode;
}
use closest(). this will get the closest ancestor that matches the selector you provide it.
$(function(){
$('a').on('click',function(){ //handler of your <a>
var ulx = $(this).closest('ul.x'); //find the closest ancestor <ul> with class "x"
});
});
For performance,
You can also use jquery on like below, jquery eventObject also has a property named delegateTarget, which could be useful in your case.
$('ul.x').on('click', 'a', function(e){
//e.delegateTarget is the parent ul of the clicked a tag
//e.target.id is the clicked a tag
alert(e.delegateTarget.id);
alert(e.target.id);
});
HTML:
<ul id='a' class="x">
<li><a id='1' href="#">A</a></li>
<li><a id='2' href="#">B</a></li>
<li><a id='3' href="#">C</a></li>
</ul>
<ul id='b' class="x">
<li><a id='11' href="#">1</a></li>
<li><a id='21' href="#">2</a></li>
<li><a id='31' href="#">3</a></li>
</ul>
In terms of performance, you are not binding the event on all the a tags. jQuery suggests this way.
Here is the fiddle.
Usually you would use .closest() like:
$('a').click(function(){
var ul = $(this).closest('ul.x'); //or just closest('ul') in case you only used the x for demo purposes
});
This will go up the DOM tree and stop at the first match (your ul.x-element).
if ul.x is direct parent of a use this:
$('a').on('click',function(){
var ul = $(this).parent('ul.x');
});
or
$('a').on('click',function(){
var ul = $(this).closest('ul.x');
});