How to call and run same function simultaneously from different <LI> using javascript or jQuery.
I want to use same function with different parameters. I want to create like Browser tabs.The multiple tabs are loading simultaneously.
(Sorry, I missed the jquery tag somehow originally.)
Using jQuery:
HTML:
<ul id="mylist">
<li>One</li>
<li>Two</li>
</ul>
JavaScript using jQuery:
$("#mylist > li").click(function() {
// Here, `this` refers to the raw DOM element.
// If you want to know which one it is by index,
// you can use $(this).index() (they start at 0).
// Or you can store information on the element
// using data-* attributes, and use
// $(this).data(...)
});
Live example
Original answer from when I'd missed the jquery tag (doh!):
There's the DOM0 way:
<li onclick="doSomething(1);">One</li>
<li onclick="doSomething(2);">Two</li>
Or there's the unobtrusive DOM0 way:
HTML:
<ul id="mylist">
<li>One</li>
<li>Two</li>
</ul>
JavaScript:
var ul = document.getElementById("mylist");
var li;
var index;
for (li = ul.firstChild; li; li = li.nextSibling) {
if (li.nodeName.toUpperCase() === "LI") {
li.onclick = makeCallback(++index);
}
}
function makeCallback(val) {
return function() {
doSomething(val);
}
}
Or the DOM2 way:
(Same HTML.)
JavaScript:
var ul = document.getElementById("mylist");
var li;
var index;
for (li = ul.firstChild; li; li = li.nextSibling) {
if (li.nodeName.toUpperCase() === "LI") {
hookEvent(li, "click", makeCallback(++index));
}
}
function makeCallback(val) {
return function() {
doSomething(val);
}
}
function hookEvent(element, eventName, handler) {
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent("on" + eventName, handler);
}
Try to use $.each:
$(...).each(function(index, Element) {
...
});
See: http://api.jquery.com/each/
For example:
$(...).each(function(index, Element) {
var target = $(this);
target.click(function() {
// when user click...
});
// something other logic...
});
$('li').click(function(){ var target = $(this);// get your target element
});
And here is the jquery way:
$("li").click(function(){
doSomething($(this).data('someValue'));
});
With the HTML holding the parameters.
<li data-someValue="one">One</li>
<li data-someValue="two">Two</li>
Add a rel attribute to the <li> element, then call the function on the <li>
$('li.your-class').bind('event_type', function(){
var ref = $(this).attr('rel');
// call your function
myFunction(ref);
}
There are quite a few outof the box solutions for this, such as jquery ui. If you wanted to do it manually you could do it fairly easily.
jQuery tabs:
http://jqueryui.com/demos/tabs/
Have your content areas named:
#main_0
#main_1
...
Then add a selector to LI
Something like:
var CurrentTabIndex = null;
$("li").live('click', function(e) {
var TabIndex = $(this).index;
var divName = "#main_" + TabIndex;
$.ajax({
url: "OpenTab.php",
data: { TabId: TabIndex },
success: function (data) {
$(divName).html(data);
$(divName).show();
if(CurrentTabIndex != null)
{
$("#main_" + CurrentTabIndex).hide();
}
CurrentTabIndex = TabIndex;
}
});
});
Related
an application I have four dropdwon -menu where one of these is filled by selecting an earlier ... this is filled in automatically ... does not respond to click event
I have searching by answers about creating a dinamic UL LI itens and found this:
function getModelos(response)
{
var obj = JSON.parse(response);
try
{
var ul = document.getElementById("modelo");
var modelos = obj.modelos;
var x = document.getElementById("modelo");
while(x.length > 0)
{
x.remove(0);
}
for(i=0;i<modelos.length;i++)
{
var li = document.createElement("li");
var a = document.createElement("a");
a.appendChild(document.createTextNode(modelos[i].modelo));
a.setAttribute("href","#");
a.setAttribute("data-value",modelos[i].id+",.modelo");
li.appendChild(a);
ul.appendChild(li);
}
}
catch(err)
{
alert("ERRO: "+err);
}
}
also I have found a click event delegating:
$(".dropdown-menu li a").click(function()
{
var selText = $(this).text();
$(this).parents('.dropdown').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
var valor = $(this).data('value');
var options = valor.split(",");
$(this).parents(".dropdown").find(options[1]).val(options[0]);
if(options[1] == ".marca")
{
pedeModelos(selText);
}
});
all dropdowm-menus previously defined response to click on LI, but this dropdown dinamic created don't
I'm new to javascript/Bootstrap/JQuery, I need a way to follow, I will apreciate any help. thanks
Like this:
$(".dropdown-menu").on("click","li a",function() {blah});
Read about Direct and delegated events
The issue is how you are delegating the click event.
If your delegation is outside the event which is creating the dynamic elements than its not going to work. Your reference to the click event should happen in the same function where you are generating the dynamic html.
For example :
<input type="button" id="btn" value="GenerateHTML"/><br/>
<div>
</div>
$("#btn").click(function()
{
$("div").append("<ul class='dropdown-menu'><li><a href='#'>1</a></li><a href='#'>2</a></ul>");
$(".dropdown-menu").find("li a").click(function()
{
alert();
});
});
http://jsfiddle.net/pkhout3x/
I created expandable content using jquery on several divs with unique ids. The code is working but now I also want to trigger this function from a top navigation using an anchor. I have tried several things but nothing works. I am very new to jquery so any help would be greatly appreciated.
I am specifically trying to invoke the click() function on each anchor.
Here is my jquery:
(function($) {
$(document).ready(function () {
var panelspeed = 500;
var totalpanels = 6;
var defaultopenpanel = 0;
var accordian = true;
var panelheight = new Array();
var currentpanel = defaultopenpanel;
var iconheight = parseInt($('.icon-close-open').css('height'));
var highlightopen = true;
//Initialise collapsible panels
function panelinit() {
for (var i=1; i<=totalpanels; i++) {
panelheight[i] = parseInt($('#cp-'+i).find('.expandable-panel-content').css('height'));
$('#cp-'+i).find('.expandable-panel-content').css('margin-top', -panelheight[i]);
if (defaultopenpanel == i) {
$('#cp-'+i).find('.icon-close-open').css('background-position', '0px -'+iconheight+'px');
$('#cp-'+i).find('.expandable-panel-content').css('margin-top', 0);
}
}
}
$('.expandable-panel-heading').click(function() {
var obj = $(this).next();
var objid = parseInt($(this).parent().attr('ID').substr(3,2));
currentpanel = objid;
if (accordian == true) {
resetpanels();
}
if (parseInt(obj.css('margin-top')) <= (panelheight[objid]*-1)) {
obj.clearQueue();
obj.stop();
obj.prev().find('.icon-close-open').css('background-position', '0px -'+iconheight+'px');
obj.animate({'margin-top':0}, panelspeed);
if (highlightopen == true) {
$('#cp-'+currentpanel + ' .expandable-panel-heading').addClass('header-active');
}
} else {
obj.clearQueue();
obj.stop();
obj.prev().find('.icon-close-open').css('background-position', '0px 0px');
obj.animate({'margin-top':(panelheight[objid]*-1)}, panelspeed);
if (highlightopen == true) {
$('#cp-'+currentpanel + ' .expandable-panel-heading').removeClass('header-active');
}
}
});
function resetpanels() {
for (var i=1; i<=totalpanels; i++) {
if (currentpanel != i) {
$('#cp-'+i).find('.icon-close-open').css('background-position', '0px 0px');
$('#cp-'+i).find('.expandable-panel-content').animate({'margin-top':-panelheight[i]}, panelspeed);
if (highlightopen == true) {
$('#cp-'+i + ' .expandable-panel-heading').removeClass('header-active');
}
}
}
}
//Uncomment these lines if the expandable panels are not a fixed width and need to resize
$( window ).resize(function() {
panelinit();
});
$(window).load(function() {
panelinit();
}); //END LOAD
}); //END READY
})(jQuery);
The html for the expandable jquery content is:
<div class="expandable-panel" id="cp-3">
<div class="expandable-panel-heading">
<h2>Testimonials<span class="icon-close-open"></span></h2>
</div>
<div class="expandable-panel-content">
<p>Panel HTML...</p>
</div>
</div>
The html anchors that I want to trigger the click() function are:
<ul class="nav">
<li class="nav">What is Justice Court Judge?</li>
<li class="nav">About Reeves Jones</li>
<li class="nav">Testimonials</li>
<li class="nav">Polling Locations</li>
<li class="nav">Map</li>
<li class="nav">Contact</li>
</ul>
Thank you in advance for your help!
If I understand correctly, you don't want to trigger the click event for the anchors, but instead you want to trigger the click event of the corresponding navigation element when an anchor is clicked.
You can do that by adding the following code inside your document-ready function:
$('.nav a').click(function() {
$($(this).attr('href')).find('.expandable-panel-heading').click();
});
This code registers a click handler on all the <a> elements inside the .nav element. It uses the href value of the clicked <a> element to get a jQuery object representing the navigation element.
In this case, you should not place the "onclick" attribute on the <a> elements.
BTW: For valid HTML, you should nest the <a> elements inside the <li> elements, not the other way around.
I recommend not to use inline event handlers.
You can add the following to your jquery code:
$(".nav").find('a').trigger("click");
$(".nav").find('a').click(function(){
//your code
})
I've been building out the functionality for this UI. These are a pair of tabs I want to write a listener for, to make my js unobtrusive. It was blocking me from going forward. Now that I'm refactoring, it's time to fix it. I want to write an event listener that gets the id of the tab that was clicked, and assigns it to a variable. This is what I have:
<ul id="gal">
<li class="glyphicons camera active" onclick="pullActive(this.id);" id="viewAll"><a href="#" ><i></i> View all photos <strong>(43) </strong></a>
</li>
<li class="glyphicons circle_plus tab-stacked" onclick="pullActive(this.id);" id="addPhotos"><i></i> <span>Add Photos</span>
</li>
</ul>
function pullActive(id){
// gets the class for that id
var getClassy = document.getElementById(id).className;
findClass(getClassy, id);
loadNew();
}
without jQuery you would have to do
var item = document.querySelector("#gal");
item.attachEventHandler("click", function(ev) {
if (ev.target.tagName === "LI") {
var id = ev.target.id;
// ...
}
});
In jquery (as you tagged your question like this) it would look like this
$(function() {
$("#gal").delegate("li", "click", function() {
var id = this.id;
// ...
});
});
jQuery solution:
$('#gal li').on('click', function () {
var className = $(this).attr('class');
var id = this).id;
console.log(className, id);
});
Vanilla solution:
[].forEach.call(document.querySelectorAll('#gal li'), function (glyphicon) {
glyphicon.addEventListener('click', function () {
var className = glyphicon.className;
var id = glyphicon.id
console.log(className, id);
});
});
Here is a fiddle containing both examples.
Using jQuery, this would be
$( document ).ready(function() {
$( '#gal' ).on( 'click', 'li', function() {
var id = this.id
});
});
The benefit of this approach is that you only have one event handler (defined on the ul) vs. having one for each li. Hope this helps.
Total js newb here.
Here is the HTML
Size 8.5
<div class="product1">
<ul class="sizeAvail" style="display:none;">
<li>8</li>
<li>8.5</li>
<li>9</li>
<li>9.5</li>
<li>10</li>
</ul>
</div>
<div class="product2">
<ul class="sizeAvail" style="display:none;">
<li>8</li>
<li>8.5</li>
<li>9</li>
<li>9.5</li>
</ul>
</div>
Here's the 'logic' of what I need...
When the user clicks the Link
Capture the id of that element
Set that as a variable
Loop through li for all ul that have class 'sizeAvail'
If li element matches variable
stop looping and move onto next ul
If ul does not have li that matches variable
set class of container div to 'hide'
This is where I'm at so far...any help would be greatly appreciated.
<script type = "text/javascript" > $(document).ready(
$(".dur").click(function () {
var clickedSize = $(this).attr("id");
$(".sizeAvail").each(function (li,+) {
alert($(this).text());
});
});
</script>
Here is a working fiddle:
http://jsfiddle.net/Hive7/uZTYf/
Here is the jquery I used:
$(".dur").click(function () {
var clickedSize = this.id;
$(".sizeAvail li").each(function () {
if($(this).text() == clickedSize) {
$(this).parent().show();
} else {
$(this).hide();
}
});
});
What you are currently doing is not right as you aren't looping through the children of .sizeAvail because you didn't directly state though what you did state wasn't in quotes like most aspects of jquery need to be.
If this still does not work make sure you have a jquery library
Or you can use the pure js option:
var $items = document.getElementsByClassName('sizeAvail');
var $dur = document.getElementsByClassName('dur');
for (i = 0; i < $dur.length; i++) {
$dur[i].addEventListener('click', durClick);
}
function durClick() {
var clickedSize = this.id;
for (i = 0; i < $items.length; i++) {
var $liElems = $items[i].getElementsByTagName('li');
for (i = 0; i < $liElems.length; i++) {
if ($liElems[i].innerHTML == clickedSize) {
$liElems[i].parentNode.style.display = 'block';
$liElems[i].style.display = 'block';
} else {
$liElems[i].style.display = 'none';
}
}
}
}
http://jsfiddle.net/Hive7/uZTYf/2/
everything you are trying to do is pretty simple syntax-wise. you can find documentation on methods to use in a number of places. you could simply use javascript for this but i am assuming you want to use jQuery
on a high level you'll want to use the jQuery selector to get all UL objects and then for each UL loop over all LI children, e.g.:
$('ul').each(function() {
$(this).find('li').each(function(){
});
});
to get the data you are looking for, you can use jQuery methods like addClass(), attr(), etc.
You may use this. Set a flag when checking all li's of a div. If none li has same value as the id, at the end hide the div.
$(document).ready(function(){
$(".dur").click(function () {
var clickedSize = this.id;
$(".sizeAvail").each(function(){
var hide = 1;
$(this).children('li').each(function(){
if(clickedSize == $(this).text()) hide=0;
});
if(hide){
$(this).closest('div').hide(); //Or $(this).parent().hide();
}
});
});
});
JSFIDDLE
You may try this too
$('a.dur').on('click', function(e){
e.preventDefault();
var id = this.id;
$('ul.sizeAvail li').each(function(){
if($(this).text() == id) $(this).closest('ul').addClass('hide');
});
});
EXAMPLE.
Demo: http://jsfiddle.net/QyKsb/
This is one way to do it, as you were doing. However, i don't, personally like cluttering html with data as that. But it maybe good choice in some situations but i dont like it.
also you cant give id a value that starts with numbers.
var products= $("div[class^='product']"),
dur =$('.dur');
dur.click(change);
function change(){
var size= $(this).data('size');
products.each(function(){
var d = $(this);
d.find('.sizeAvail>li').each(function(){
d.hide();
if($(this).text()==size) { d.show(); return false;}
});
});
}
You can use a combination of not, has and contains selectors to get the matched elements and set a class on them using addClass.
Ref:
http://api.jquery.com/not-selector/
http://api.jquery.com/has-selector/
http://api.jquery.com/contains-selector/
http://api.jquery.com/addClass/
Code:
$(".dur").click(function () {
$(".sizeAvail:not(:has(li:contains('"+$(this).prop("id")+"')))").addClass('hide')
});
Demo: http://jsfiddle.net/IrvinDominin/t8eMD/
I am trying to get the class or an id of the last clicked element. This is what I have based off of what I found here...
HTML
Button
JQUERY
$('.button').click(function () {
myFuntion();
});
function myFunction (e) {
e = e || event;
$.lastClicked = e.target || e.srcElement;
var lastClickedElement = $.lastClicked;
console.log(lastClickedElement);
}
This sort of does what I want, but I am not sure how to go about modifying it so I can get just the class.
I have also tried using this solution but couldn't get it to work with my code.
$('.button').click(function () {
myFuntion();
});
function myFunction(){
var lastID;
lastID = $(this).attr("id");
console.log(lastID);
}
When I do this my console log comes back as undefined. I am probably missing something obvious. Any help is much appreciated. Thanks.
You can pass clicked element as parameter to your function:
$('.button').click(function () {
myFunction(this);
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
UPDATE added jsfiddle
A couple of ways come to mind:
$(".button").click(myFunction);
Should work with the above myFunction.
$(".button").click(function () { myFunction($(this)); });
function myFunction($elem) {
var lastID;
lastID = $elem.attr('id');
$.data('lastID', lastID);
}
In order to get the class-name of the element, assuming you have an accurate reference to the element from which you want to retrieve the data:
var lastClickedElement = $.lastClicked,
lastClickedElementClassNames = lastClickedElement.className;
This does return the full list of all the classes of the element though.
$('.button').click(function () {
myFuntion(this);
});
function myFunction(ele){
var lastID;
lastID = $(ele).attr("id");
console.log(lastID);
}
First Select all possible DOM Elements
var lastSelectedElement = null
$(document).ready(function(){
$("*").live("click",function(){
lastSelectedElement = $(this);
myFunction($(this));
});
});
function myFunction(element) {
console.log(element);
console.log(element.id);
console.log($(element).attr("class"));
}
than you could play with lastSelectedElement by grabbing it's ID or Class with jQuery .attr("ID OR CLASS");