How can I break out of an each() in jQuery? - javascript

I have the following HTML + JS. I want the toggleButton to only toggle the first io-section-header. Eventually I will have multiple toggleButton's that will toggle a unique ul.
How can I achieve this?
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div><span>Section 1</span></div>
<div class="io-section-header">
<ul>
<li class="advanced">Accounts</li>
<li class="advanced">People</li>
<li class="advanced">companies</li>
<li class="basic">She</li>
</ul>
<div><span>Section 2</span></div>
<div class="io-section-header">
<ul>
<li class="advanced">Accounts</li>
<li class="advanced">People</li>
<li class="advanced">companies</li>
<li class="basic">P</li>
</ul>
</div>
</div>
<div class="toggleButton">Collapse</div>
<script>
jQuery(function ($) {
$('.toggleButton').click(function () {
var currentText = $(this).text();
if(currentText === "Collapse")
$(this).text("Expand");
else
$(this).text("Collapse");
/*$('.io-section-header').each(function() {
$("li").siblings(".advanced").toggle('fast',function(){});
});*/
$('.io-section-header li').siblings(".advanced").toggle('fast');
});
});
</script>
</body>
</html>

From the .each() documentation:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

This will toggle the first advanced class in each io-section-header class
$('ul li.advanced:first', '.io-section-header').toggle('fast',function(){});
This will toggle the first advanced class in the first io-section-header class
$('ul li.advanced:first', '.io-section-header:first').toggle('fast',function(){});

return false is all you need; why aren't you using first()?

Related

Change value of html element by classname using javascript

Here is my HTML code:
<li class="list-promotions">
<ul class="list-promotions-item">
<li>
offers
</li>
</ul>
</li>
I try to use this javascript code: (This Thread)
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByClassName("classname")[0].innerHTML = "qwerty";
});
It works, but it changes my HTML to:
<li class="list-promotions">
<ul class="list-promotions-item">qwerty</ul>
</li>
So I lost <a> tag and the href .
How I can solve this issue? I just want to change the offers to another text and keep the <a> tag
Note: I do not have access to the HTML code to set a class name for <a> tag and use the above javascript code.
document.querySelector(".list-promotions-item > li > a").textContent = "qwerty";
The innerHTML property sets or returns the HTML content (inner HTML)
of an element.
You had not added the classname class in HTML to anchor tag.
<li class="list-promotions">
<ul class="list-promotions-item">
<li>
offers
</li>
</ul>
</li>
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementsByClassName("classname")[0].innerHTML = "qwerty";
});
You can learn more at: https://www.w3schools.com/jsref/prop_html_innerhtml.asp
Using Jquery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.list-promotions-item li a').html('qwerty');
});
</script>
</head>
<body>
<li class="list-promotions">
<ul class="list-promotions-item">
<li>
offers
</li>
</ul>
</li>
</body>
</html>

Element does not appear if order changed

I displayed 3 li elements with HTML and 3 using JavaScript code. If I change my JavaScript div tag to last it displays both the ul elements, else it's not displaying the HTML ul tags. Can you tell me why?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>my javascript eg </title>
<script type="text/javascript" >
function process()
{
var sval="<ul> <li> orange</li> <li>blue</li> <li>green</li> </ul> ";
var divid=document.getElementById("mydiv");
divid.innerHTML=sval;
}
</script>
</head>
<body onload="process()">
Hi Dude !!!
<div id="mydiv"/>
<ul id="u2" onclick="fn1()">
<li>orange</li>
<li>blue</li>
<li>yellow</li>
</ul>
<!-- If I place the same div element at last line it doesn't work. -->
</body>
</html>
use class instead of id, class is used for multiple elements
JS
function process()
{
var sval="<ul> <li> orange</li> <li>blue</li> <li>green</li> </ul> ";
var divclass=document.getElementsByClassName("mydiv");
for (var i = 0;i<divclass.length;i++){
var item = divclass[i];
item.innerHTML=sval;
}
}
HTML
<body onload="process()">
Hi Dude !!!
<div class="mydiv"></div>
<ul id="u2" onclick="fn1()">
<li>orange</li>
<li>blue</li>
<li>yellow</li>
</ul>
<div class="mydiv"></div>
</body>
Demo: http://jsfiddle.net/5avtsqnz/6/
It is because you cannot have more than one element in the DOM with the same id. If you do so you will always get only the first element with the id.
See the code, its getElementById and not getElementsById. So it it always return a single element.
Try this<------------HTML Code--------->SEE THIS YOUR CODE: http://jsfiddle.net/fbwyyrcL/
<body onload="process()">
Hi Dude !!!
<div id="mydiv"></div>
<ul id="u2" onclick="fn1()">
<li>orange</li>
<li>blue</li>
<li>yellow</li>
</ul>
</body>
<------------Script code is------->
function process()
{
var sval="<ul> <li> orange</li> <li>blue</li> <li>green</li> </ul> ";
var divid=document.getElementById("mydiv");
divid.innerHTML=sval;
}
You just have just to close your div tag properly, or to create another div around your primary ul definition. If you leave the inital ul inside the "mydiv" div, it is overwritten (deleted) after your function run.
Following code has worked for me in IE9:
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>my javascript eg</title>
<script type="text/javascript" >
function prozess(){
var sval="<ul> <li> orange</li> <li>blue</li> <li>green</li> </ul>";
var divid=document.getElementById("mydiv");
divid.innerHTML=sval;
};
</script>
</head>
<body onload = "prozess()">
Hi Dude !!!
<div id="mydiv"> </div>
<ul id="u2" onclick="fn1()">
<li>orange</li><li>blue</li><li>yellow</li>
</ul>
</body>
</html>

how to pass this element to javascript onclick function and add a class to that clicked element

I had an html navigation code as below
function Data(string) {
//1. get some data from server according to month year etc.,
//2. unactive all the remaining li's and make the current clicked element active by adding "active" class to the element
$('.filter').removeClass('active');
$(this).addClass('active');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter">This Month</li>
<li class="filter">Year</li>
<li class="filter">60 Days</li>
<li class="filter">90 Days</li>
</ul>
</div>
When the user clicks on any of the tabs
all the remaining tabs should be unactive,
and the current element/tab should be active,
My code above is not working.
How to make the above code work?
I only want to use javascript onclick for this. Is there any way that the this(current) object is send when the user clicks on the tab?
Use this html to get the clicked element:
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter">This Month</li>
<li class="filter">Year</li>
<li class="filter">60 Days</li>
<li class="filter">90 Days</li>
</ul>
</div>
Script:
function Data(string, el)
{
$('.filter').removeClass('active');
$(el).parent().addClass('active');
}
Try like
<script>
function Data(string)
{
$('.filter').removeClass('active');
$(this).parent('.filter').addClass('active') ;
}
</script>
For the class selector you need to use . before the classname.And you need to add the class for the parent. Bec you are clicking on anchor tag not the filter.
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter">This Month</li>
<li class="filter">Year</li>
<li class="filter">60 Days</li>
<li class="filter">90 Days</li>
</ul>
</div>
<script>
function Data(element)
{
element.removeClass('active');
element.addClass('active') ;
}
</script>
You have two issues in your code.. First you need reference to capture the element on click. Try adding another parameter to your function to reference this. Also active class is for li element initially while you are tryin to add it to "a" element in the function.
try this..
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter">This Month</li>
<li class="filter">Year</li>
<li class="filter">60 Days</li>
<li class="filter">90 Days</li>
</ul>
</div>
<script>
function Data(string,element)
{
//1. get some data from server according to month year etc.,
//2. unactive all the remaining li's and make the current clicked element active by adding "active" class to the element
$('.filter').removeClass('active');
$(element).parent().addClass('active') ;
}
</script>
You can use addEventListener to pass this to a JavaScript function.
HTML
<button id="button">Year</button>
JavaScript
(function () {
var btn = document.getElementById('button');
btn.addEventListener('click', function () {
Date('#year');
}, false);
})();
function Data(string)
{
$('.filter').removeClass('active');
$(this).parent().addClass('active') ;
}
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick(event)
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = event.target || event.srcElement; // IE
console.log(target);
console.log(target.src);
var img = document.createElement('img');
img.setAttribute('src', target.src);
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
</body>
</html>

jQuery .show & .hide not working

I am currently working on building a small menu that will change divs based upon which one it clicked. So if one is clicked it will show the div associated with it and hide the others, ect. But I cannot get it to work, nor can I figure out why. Any help would be appreciated. Thanks.
Below is my code. I've clipped out the content as there was a lot of it.
<script type="text/javascript">
$('.mopHeader').click(function() {
$('#raid-progress-mop').show();
$('#raid-progress-cata').hide();
$('#raid-progress-wotlk').hide();
$('#raid-progress-tbc').hide();
$('#raid-progress-vanilla').hide();
});
$('.cataHeader').click(function() {
$('#raid-progress-mop').hide();
$('#raid-progress-cata').show();
$('#raid-progress-wotlk').hide();
$('#raid-progress-tbc').hide();
$('#raid-progress-vanilla').hide();
});
$('.wotlkHeader').click(function() {
$('#raid-progress-mop').hide();
$('#raid-progress-cata').hide();
$('#raid-progress-wotlk').show();
$('#raid-progress-tbc').hide();
$('#raid-progress-vanilla').hide();
});
$('.tbcHeader').click(function() {
$('#raid-progress-mop').hide();
$('#raid-progress-cata').hide();
$('#raid-progress-wotlk').hide();
$('#raid-progress-tbc').show();
$('#raid-progress-vanilla').hide();
});
$('.vanillaHeader').click(function() {
$('#raid-progress-mop').hide();
$('#raid-progress-cata').hide();
$('#raid-progress-wotlk').hide();
$('#raid-progress-tbc').hide();
$('#raid-progress-vanilla').show();
});
</script>
<span class="h4">Raid Progress <span class="mopHeader">MoP</span> <span class="cataHeader">Cata</span> <span class="wotlkHeader">WotLK</span> <span class="tbcHeader">TBC</span> <span class="vanillaHeader">WoW</span></span>
<div id="raid-progress-mop">
<ul id="raid-mop">
<li>Content A</li>
</ul>
</div>
<div id="raid-progress-cata">
<ul id="raid-cata">
<li>Content B</li>
</ul>
</div>
<div id="raid-progress-wotlk">
<ul id="raid-wotlk">
<li>Content C</li>
</ul>
</div>
<div id="raid-progress-tbc">
<ul id="raid-tbc">
<li>Content D</li>
</ul>
</div>
<div id="raid-progress-vanilla">
<ul id="raid-vanilla">
<li>Content E</li>
</ul>
</div>
Wrap your code in:
$(function(){ ... });
...which is the short form of:
$(document).ready(function(){ ... });
Cheers
You need to put the script underneath your markup. Either that, or put it inside document.ready callback:
$(document).ready(function() {
// code here
});
The problem is that when the script appears above the markup, it will execute before the HTML is loaded, and so the browser won't yet know about raid-progress-mop, etc.
How about doing that a little more dynamically inside a ready() function :
<script type="text/javascript">
$(function() {
$('[class$="Header"]').on('click', function() {
var myClass = $(this).attr('class').replace('Header', '');
$('[id^="raid-progress"]').hide();
$('#raid-progress-' + myClass).show();
});
});
</script>
jsBin demo
Wrap your code into a ready finction and this code I wrote is all you need:
$(function(){
$('span[class$="Header"]').click(function(){
var classNameSpecific = $(this).attr('class').split('Header')[0];
$('div[id^="raid-progress-"]').hide();
$('#raid-progress-'+classNameSpecific).show();
});
});
Explanation:
$('span[class$="Header"]') = target any span element which class ends with Header
Now just attach a click handler to all that spans.
Than, to hide all your div elements do:
$('div[id^="raid-progress-"]').hide(); = will hide any div which id starts with raid-progress-
and than you just need to target the div that contains the magic word:
$('#raid-progress-'+classNameSpecific).show();
$('.mopHeader') isn't defined yet. wrap your script with $(function(){...})

adding extra identifiers to dom elements

I have a bunch of menu items in a list format like so
<ul class="menu unselectable">
<li class="group">
Group Title
<ul>
<li class="groupItem i0">item 0</li>
<li class="groupItem i1 over">item 1</li>
</ul>
</li>
<li class="group">
Another Group Title
<ul>
<li class="groupItem i2">item 2</li>
<li class="groupItem i1">item 1 (if I hover here, the others should too</li>
</ul>
</li>
</ul>
The idea is, if I hover on one item with class i1 then all i1 items should behave the same. So I thought of adding a class over to all i1 items when I hover on any of them like so.
$(".groupItem").hover(
function () {
$(this).addClass("over");
},
function () {
$(this).removeClass("over");
}
);
The problem is I can't think of a way to identify what item has just been hovered on aside from $(this). To remedy this I thought of adding i1 as an id to items, but different dom nodes shouldn't have the same id. My next idea was to add the attribute value to the li items but to no avail (when I did a quick test with $(this).val() kept returning 0 regardless of the value actually stored in the node.
Is there any way I can add an identifier so I can just say $(this).<someIdentifier> , and target all the dom nodes with that identifier?
you can add an attribute groupID="{id}" and then call $(this).attr('groupID')
Element.prototype.secondId = '';
and than
document.getElementById('id5').secondId = 13;
As this you just set on any element a new property which you can use as you wish but is just in javascript not in html.
I don't recommend adding false attributes to elements, and this will work even if data attributes are not well supported by the user's browser:
$(".groupItem").hover(
function () {
var className = this.className.split(' ')[1];
$('.' + className).addClass("over");
},
function () {
var className = this.className.split(' ')[1];
$('.' + className).removeClass("over");
}
);
NOTE: Requires that classes are always organized as you specified above. A safer way could be:
var className = $.trim(this.className.replace('groupItem',''));
$(this).filter('#selector')
Please, Try working below code as below once:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<style>
.menu{ display:inline;}
.menu li{ display:inline; float: left;width: 100px;}
.menu li ul{display:none;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".group").hover(
function () {
$(this).find("ul").show();
},
function () {
$(this).find("ul").hide();
}
);
});
</script>
</head>
<body>
<ul class="menu">
<li class="group">
Group Title
<ul>
<li>GT 1</li>
<li>GT 2</li>
</ul>
</li>
<li class="group">
Trochlear Nerve
<ul>
<li>TN 1</li>
<li>TN 2</li>
</ul>
</li>
</ul>
</body>
</html>

Categories