detect clicking different index of the same class or element - javascript

I have a navigation with ul li in it
<nav>
<ul>
<li id="zero"></li>
<li id="one"></li>
<li id="two"></li>
</ul>
</nav>
for javascript I have event handler to detect the index I click on. But how do I write a if condition if the current click on the li is different from the previous one?
$('li').click(function(){
var indexNum = $(this).index();
if( prevIndexNum != currentIndexNum ){
//do something
}
})
I guess this is more of a question on how to store the previous variable value? Any read on it greatly appreciated.

You just need to save off the last one clicked.
var prevIndexNum;
$('li').click(function() {
var indexNum = $(this).index();
if (prevIndexNum !== indexNum) {
console.log('different');
prevIndexNum = indexNum;
} else {
console.log('same');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="zero">zero</li>
<li id="one">one</li>
<li id="two">two</li>
</ul>

You need to store the the current index in local variable, if the codition is true which is not equal, move the current index to the global variable which we are going to called prevIndexNum. I hope it will help you a lot.
var prevIndexNum;
$('li').click(function(){
var currentIndexNum = $(this).index();
if( prevIndexNum != currentIndexNum ){
//do something if the value are not the same.
} else {
// do something if the value are the same.
}
})

add
var prev
if(indexNum != prev)
prev = $(this).index()
before.
As the other guy mentioned all you really have to do is save the value from the previous run through the code.

Related

Finding the text inside this element

I'm looking to make a fairly simple operation: you click on an li, you get the text inside, using JavaScript (not JQuery). What I can't figure out (or find out) is how to get the innerHTML.
function enable() {
document.addEventListener('click', e => {
if (e.target.classList.contains('refine-menu-li')) {
var selected = this.innerHTML;
console.log('stuff'); // Working
console.log(selected); // Not working
}
});
}
Is the problem that I am using class and so require a for-loop? Or is this a foolish thing to try and use?
Thanks!
You could try something like this, without using an arrow function:
document.getElementById("js-list")
.addEventListener("click",function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log(e.target.innerHTML);
}
});
<ul id="js-list">
<li>value1</li>
<li>value2</li>
<li>value3</li>
</ul>
Arrow functions capture this from the context they are declared in.
this.innerHTML is not the innerHTML you are looking for.
You probably want e.target.innerHTML.
If you weren't using an arrow function, then this will wouldn't be the value you wanted. Event handlers are called in the context of the element they are bound to (document in this case), not the element that triggered the event.
Try this
function enable() {
document.addEventListener('click', e => {
var current = e.target;
if (e.target.classList.contains('refine-menu-li')) {
var selected = current.innerHTML;
console.log('stuff'); // Working
console.log(selected); // Not working
}
});
}
enable();
<ul>
<li class='refine-menu-li a'>1 </li>
<li class='refine-menu-li b '>2</li>
<li class='refine-menu-li c '>3</li>
<li class='refine-menu-li d'>4</li>
</ul>

JQuery delete closest element from Firebase

So I append my chatbox with records from Firebase, but I would also like to delete those records. Now I am not a genious with JQuery and thus I would like to know what should be used. In the original example they use data-id's
//Delete when clicking element
jQuery('body').on('click', 'a#message', function() {
var $rec = $(this).closest('[data-reactid]');
var id = $rec.attr('data-reactid') || null;
if( id ) {
// Delete nested elements
$rec.find('[data-reactid]').each(function() {
ref.child($(this).attr('data-reactid')).remove();
});
// Delete record
ref.child(id).remove();
}
return false;
});
ref.on('child_removed', function (snapshot) {
$('ul.chat-messages').find('[data-reactid="'+snapshot.name()+'"]').remove();
});
This is the original example:
http://jsfiddle.net/katowulf/QnUpb/
My output is a bit else than the example, it is build as follow:
<ul class="chat-messages" data-reactid=".1.1.1.1">
<ul id="ulrecords">
<li id="limessage">[some message here]</li>
<li>[additional info for message</li>
</ul>
</ul>
Basically in the first 'li' i have a to activate the JQuery and when i click that delete button in the 'li', I want to delete the "ulrecords"
Hope anyone can help me with this

Loop through list using Jquery

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/

How do I use jquery to get the Next/Previous Page(s)

when click next button will redirect to next li
<div id="mainmenu">
<ul id="menu">
<li class="active">Home</li>
<li >News</li>
<li >Sports</li>
</ul>
next
prev
I assume you want to cycle through those <li>s based on where the active class currently is?
Well, to get the next, you could use the ... next method :)
$('.next').click(function(){
var $current = $('li.active');
var $next = $current.next();
if ($next.length){
window.location = $next.find('a').attr('href'); //I assume???
} else {
//let's wrap around to the first li in the list, per TJ's comment
var $wrapAroundTarget = $current.siblings().first();
window.location = $wrapAroundTarget.find('a').attr('href');
}
});
And of course previous would be the same thing, but with the prev method instead of next, and, per TJ again, to wrap around to the last <li>, simply use $current.siblings().last().
How about this?
$('a.next').click(function() {
$('#mainmenu li.active').next().each(function () {
window.location = $(this).find('a').attr('href');
});
});
$('a.prev').click(function() {
$('#mainmenu li.active').prev().each(function () {
window.location = $(this).find('a').attr('href');
});
});
If you can guarantee that the you don't try to go prev from the first link or next from the last one (by hiding the links, etc), the code could be simplified significantly:
$('a.next').click(function() {
window.location = $('#mainmenu li.active').next().find('a').attr('href');
});
$('a.prev').click(function() {
window.location = $('#mainmenu li.active').prev().find('a').attr('href');
});

compare url string and menu string then add class using jquery

I have a URL which looks like this:
http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx
I have a UL LI menu on the page:
<ul>
<li>Test</li>
<li>Hello</li>
<li>Bye</li>
<li>Something</li>
<li>Cars</li>
</ul>
I am having the menu on every page and would like to use jquery to check that im on that page. If i am then make the A/li bold so the user knows they are on the page.
I have tried the following:
$(document).ready(function () {
if(window.location.href.indexOf("test")) //
{
alert("your url contains the name test");
}
});
But id like something that doesnt involve hard coding the values of the URL string. As if the user decides to add more links to the UL/LI the jquery needs to check the link and the url automatically and add a class to the LI (so that i can style it).
Hopefully thats enough infomation.
The issue is because the indexOf() method returns -1 when the value is not found. You need to check for that value, not coerce the result to a boolean as you currently are. Try this:
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
You would need to make the selector a bit more specific, something like #menu a
This?
$('ul#menu a').each(function() {
if(window.location.href.indexOf($(this).attr('href')) !== -1) {
$(this).closest('li').addClass('yourClass');
}
});
I added an id menu to your ul to basically differentiate your menubar with other uls that may be in the same page. also !== -1 as indexOf returns -1 if it can't find the string searched in the argument.
indexOf returns -1 if the string is not contained:
(document).ready(function () {
if(window.location.href.indexOf("test") != -1) //
{
alert("your url contains the name test");
}
});
$(document).ready(function () {
var liTest = $('ul > li'); // ' was missing
liTest.each(function() {
if(window.location.href == $('a', this).attr('href')) //
{
$(this).css('font-weight', 'bold');
return;
}
});
});

Categories

Resources