How to iterate through jquery selection - javascript

I am trying to figure out how jquery selectors work when selecting a group of elements. Once i have the all of the elements i am trying to iterate through and check a style value of them to find which one has that and it does not seem to work. Do i have to iterate through them differently? Thank you for any help. I have tried searching and messing with it and this is what i have as of now.
function toggle() {
//get all the content divs
var $all_divs = $('.content_div');
//find the content div that is visable
var $active_index = -1;
for (i = 0; i < $all_divs.length(); i++) {
if ($all_divs[i].style.display == "block") {
$active_index = i;
}
}
$all_divs[$active_index].style.display = "none";
}
edit:
Some more info on where i am headed with this.
Basically i have 4 divs, and when i click a button i want the one that is visible to go away, and the next one in the list to appear.
Whole code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style type="text/css">
.wrapper {
width:450px;
height:30px;
position:relative;
}
.slide_button {
width:25px;
height:30px;
position:absolute;
top:0;
}
#left {
left:0;
}
#right {
left:425px;
}
.content_div {
width:400px;
height:30px;
position:absolute;
top:0;
left:25px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
function toggle() {
var Divs = $('.content_div');
var i;
var index = 0;
Divs.each(function(index) {
if ($(this).css('display') == 'block')
i = index;
index++;
});
if(typeof i !== 'undefined'){
Divs.eq(i).css('display', 'none');
}
}
</script>
</head>
<body>
<div class="wrapper">
<div class="slide_button" id="left">
<center><a href='javascript:toggle();'><</a></center>
</div>
<div id='div1' class='content_div' style="display:block;">
this is div 1
</div>
<div id='div2' class='content_div' style="display:none;">
this is div 2
</div>
<div id='div3' class='content_div' style="display:none;">
this is div 3
</div>
<div class="slide_button" id='right'>
<center>></center>
</div>
</div>
</body>
</html>

I think the reason your code doesn't work is the use of .length() in the for loop condition. jQuery objects don't have a .length() method, they have a .length property. Drop the brackets and your code should work.
EDIT: For your requirement to display the divs one at a time you can do something like this:
$(document).ready(function() {
var $divs = $("div.content_div").hide(), // first hide all the divs
i = 0;
$divs.eq(i).show(); // then show the first
$(".slide_button a").click(function() {
$divs.eq(i).hide(); // on click hide the current div
i = (i+1) % $divs.length; // then update the index to
$divs.eq(i).show(); // show the next one
});
});
Demo: http://jsfiddle.net/7CcMh/
(The rest of my original answer:)
The syntax you are using to access the individual elements is OK: if $all_divs is a jQuery object, which it is, then $all_divs[0] is a reference to the first DOM element in the jQuery object. However, jQuery provides the .each() method to make this process easier:
$('.content_div').each(function() {
// here 'this' is the current DOM element, so:
if (this.style.display == "block")
this.style.display = "none";
// OR, to access the current element through jQuery methods:
$(this).css("display", "none");
});
Having said that, it seems you expect all but one element to be hidden already and you are finding that one and hiding it too. If so, you can achieve that in one line:
$('.content_div').hide();
// OR
$('.content_div').css("display", "none");
jQuery methods like .hide() and .css() apply to all elements in the jQuery object they're called on.

You can use jQuery each() method which lets you iterate through the selected elements.
$('.content_div').each(functon(index){
if ($(this).is(':visible')) {
$(this).hide()
}
})
If you want to select the visible divs you can use the :visible selector:
Selects all elements that are visible.
$('.content_div:visible').css('display', 'none'): // or $('.content_div:visible').hide()
update:
you can add a class to the anchor and try the following:
<center>></center>
$('.toggle').click(function(e){
e.preventDefault()
if ($('.content_div:visible').next('.content_div').length != 0) {
$('.content_div:visible').hide().next('.content_div:hidden:first').show()
} else {
$('.content_div').hide().eq(0).show()
}
})
Demo

Use the standard each method from JQuery.
$('.content_div').each(function(index) {
// do work with the given index
if (this.style.display == "block") {
this.style.display = "none";
}
});

Last changes:
http://jsfiddle.net/6fPLp/13/

Related

Contenteditable add/remove class if child id :focus

I have a div set as contenteditable and everything inside of that div can be edited. Now when I click on the div I automatically add a class selected (If visible prior I remove it and add it to the new selection) I have next and forward buttons so I can change my selection if I'm on using a tablet or smart phone.
Now here's where I need help.
So I selected the middle div and as I move my cursor to another child of #dynamic-storage I'm left with the problem of removing the class selected and adding it to the new child that's selected. (Not the span in the example as it's parent is a div. That's what I want selected as the div's in this example are the children of #dynamic-storage (ex. #dynamic-storage > div)
The snippet provided at the bottom of this post does not contain the arrows or menubar provided in the screenshot and fiddle links above as that code is not necessary at the given time of posting. I'm keeping this post focused on the one task being handling the .selected class for the focused child of #dynamic-storage.
$(document).ready(function() {
// Select Elements
var SelectElements = function() {
$("#dynamic-storage").children().on("mouseup touchend", function() {
if ( $(".selected").is(":visible") ) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
};
// Clear Selection
var ClearSelection = function() {
$(".selected").removeClass("selected");
};
SelectElements();
// Handles Hotkeys
$(document).keyup(function(e) {
// Up & Down Arrow Keys To Select/Deselect Element in Editable
if (e.which === 38 || 40 ) {
if ( $(".selected").is(":focus") ) {
alert("correct");
} else if ( $(".selected").is(":blur") ) {
alert("incorrect");
}
}
});
});
/* Body */
#dynamic-storage {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 0;
outline: 0;
}
#dynamic-storage .selected {
outline: 2px dotted #69f;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<link type='text/css' rel='stylesheet' href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="dynamic-storage" contenteditable="true">
<div class="header" align="center">
<h1>Welcome</h1>
<h5>My name is Michael.</h5>
<span>Hello world</span>
</div>
<div class="header selected" align="left">
<h1>Welcome</h1>
<h5>My name is Michael.</h5>
</div>
<div class="header" align="right">
<h1>Welcome</h1>
<h5>My name is Michael.</h5>
</div>
</div>
</body>
</html>
Fiddle: http://liveweave.com/uyz4VK
Fiddle: http://jsbin.com/kujuxofeju/1/edit?html,js,output
Element with attribute contenteditable='true' has all its content editable as in a single textarea. That is the reason why focus/blur event will not happen when you move cursor. Everywhere inside element with contenteditable='true' you are still in the same textarea not leaving or entering it.
The solution here is to deal with coursor positioning similar to textarea.
To get an object that represents current selection we use function:
var getSelection;
if (window.getSelection) {
// IE 9 and non-IE
getSelection = function() {
var sel = window.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
} else if (document.selection && document.selection.createRange) {
// IE <= 8
getSelection = function() {
var sel = document.selection;
return (sel.type != "None") ? sel.createRange() : null;
};
}
Then we need to do the next operations: remove class .selected from the first level children of #dynamic-storage, get element with cursor, and go up the DOM to find its parent closest to #dynamic-storage to add class .selected:
// Handles Hotkeys
$(document).keyup(function(e) {
// Up & Down Arrow Keys To Select/Deselect Element in Editable
if (e.which === 38 || 40 ) {
$('#dynamic-storage > div').removeClass('selected');
var selectedElem = getSelection()[0].commonAncestorContainer.parentElement;
$(selectedElem).closest('#dynamic-storage > div').addClass('selected');
}
});
Here is the working fiddle
Something along the lines of (try this in your main jQuery function) :
$("#dynamic-storage").children().each(function() {
$(this).on("focus", function() {
$(this).addClass("selected");
});
$(this).on("blur", function() {
$(this).removeClass("selected");
});
});
But if you edit the contents, you will loose the event handlers bound to them ...

'href' Not Showing Output on Click

Im trying to have a href link expand/display extra text when clicked however when I click it nothing happens.
When I run the html code I can click on the link but it does not show the text for some reason.
Any idea why?
Heres the code:
<html>
click to expand
<div id="divID" style="display: none;">this is expanded</div>
</html>
I'm trying to keep the code as short as possible as the above code will have to be repeated hundreds of times for each link.
Assuming you're using jQuery, you are using the CSS selector incorrectly. Your line should be this:
click to expand
The # in #divID represents any element with an id of divID, whereas just using divID will search for divID tags (something like <divID></divID>)
See here for more documentation on the ID Selector and here's a list of all the CSS selectors you can use, including the Element Selector for you to understand why your previous code didn't work.
You can also combine CSS selectors to narrow your selection in the future, although it's not much necessary with an ID selector:
click to expand
And if you absolutely insist on not using jQuery:
click to expand
or breaking it out into its own function:
<script>
function toggleElementById(id) {
if (document.getElementById(id).style.display == 'none') {
document.getElementById(id).style.display = 'block';
} else {
document.getElementById(id).style.display = 'none';
}
}
</script>
click to expand
Add this to your page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then:
$('#divID').toggle();
I see you're using jQuery, right? So I wrote your answer in jQuery..
$('.toggle').click(function () {
var selected = $(this).attr('href');
$('.expandable'+selected).toggle();
});
Check out the jsfiddle
If you're not using jQuery than here is the javascript version (html changed).
var expandable = document.getElementsByClassName("expandable");
for (i = 0; i < expandable.length; ++i) {
expandable[i].setAttribute('style','display: none;');
}
var toggle = document.getElementsByClassName("toggle");
for (i = 0; i < toggle.length; ++i) {
toggle[i].setAttribute('onclick','toggler(this)');
}
function toggler(obj) {
var id = obj.dataset.toggle,
el = document.getElementById(id);
el.style.display = (el.style.display != 'none' ? 'none' : '');
}
Check out the jsfiddle

How to select a div with specific css property

//style
.TemplateBox1{display:none;}
//Html
<div class="TemplateBox1" id="9"> 1 </div>
<div class="TemplateBox1" id="10"> 2 </div>
<div class="TemplateBox1" id="11"> 3 </div>
//jQuery
$('div', this).each(function (e) { //Do something });
This is a part from my code, at start the divs display (CSSproperty) is none (not shown) and after the user click on a certain button the property of the div changed to block (shown). I need to select only the divs that their property is display:block using jQuery, I tried :
$('div', this).**css("display")=="block"**.each(function (e) { //Do something }); - didn't work..
What do I need to add to my jQuery...
Try to use :visible selector,
$('div:visible')
It seems that you are using TemplateBox1 class to hide those elements, so you can write in this manner too, that is by using :not() selector
$('div:not(.TemplateBox1)')
Try this : :visible selector for div
$(this).find('div:visible').each(function(){
// do stuff here
});
one way is $('div:visible')
another way is (Demo)
$('.TemplateBox1', this).each(function (e) {
var $css = $(this).css('display');
if($css == 'none'){
$(this).css('display','block')
}
});
Why not use pure JS ?
var list = document.getElementsByTagName("div");
foreach(var i = 0;i < list.length, i++)
{
if(list[i].style.display == "block")
{
// do Something;
}
}

jQuery show div with same number suffix as first child of element

First off I'd like to apologise for asking about something so specific but it's been wracking my brain all day and I'm out of ideas.
I'm using jquery to show and hide elements based on their number suffix ie:
<span></span> will target ->
<div class="content" id="cont-1">This is content</div> and it's working perfectly. I'd like to target another element based on the suffix of another element but I'm failing to. Here's the code:
HTML:
<script src="http://code.jquery.com/jquery.js"></script>
1
2
3
<div class="content" id="cont-1"><p>This is content</p></div>
<div class="content" id="cont-2"><p>This is content</p></div>
<div class="content" id="cont-3">
<div class="child" id="child-11"><p>This is the first child</p></div>
<div class="child" id="child-12"><p>This is the second child</p></div>
</div>
<div class="external" id="external-11"><p>I am the first external</p></div>
<div class="external" id="external-12"><p>I am the second external</p></div>
JAVASCRIPT:
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' ){
$('#cont-'+num).fadeIn();
}else{
$('#cont-'+num).fadeOut();
}
}
CSS:
.content{
background:green;
color:white;
padding:5px;
}
.external{
background:blue;
color:white;
padding:5px;
}
.content, .external, .child{
display:none;
}
.active{
display:block;
}
CodePen: http://codepen.io/anon/pen/uFpzE
What I'm trying to achieve is this:
If you click on #tab-3 the .external div that corresponds with the first child of #cont-3 should show.
I've tried this:
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
var random = $('#cont'+num + '.child:first-child').attr('id').replace(/child-/, '');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none'){
$('#cont-'+num).fadeIn();
$('#external'+random).fadeIn({'duration':600,'queue':false});
}else{
$('#cont-'+num).fadeOut();
}
}
...and it isn't working. Where am I going wrong?
I'm not 100% sure what you're trying to accomplish with the code in the document.ready part, but the showCont function does what you requested.
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num)
{
$('.content').fadeOut(300);
$('.external').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
// get the child element's id
var targetID = $("#cont-"+num).children().first().attr('id');
if(targetID)
{
// construct the id of the external element
$('#external-'+targetID.substring(targetID.indexOf('-')+1))
.fadeIn({'duration':600,'queue':false});
}
}
else
{
$('#cont-'+num).fadeOut();
}
}
DEMO
The variable random is not defined in your JS file, and there are some typos regarding the selector elements (e.g. it should be $('#external-'+random) instead of $('#external'+random)). Base on your code, I came up with the following for your reference:
DEMO
var $ = jQuery;
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
var random = $('#cont-'+num + ' div:first-child').attr('id').substring(6);
$('#external-'+random).fadeIn({'duration':600,'queue':false});
}
else
{
$('#cont-'+num).fadeOut();
var random = $('#cont-'+num + ' div:first-child').attr('id').substring(6);
$('#external-'+random).fadeOut({'duration':600,'queue':false});
}
}
I think you've got random in the wrong function. The #cont and #external selectors are also missing a trailing dash:
$(document).ready(function(){
$('.content .child:nth-child(1)').addClass('active');
});
function showCont(num){
var random = $('#cont-'+num + '.child:first-child').attr('id').replace(/child-/, '');
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none'){
$('#cont-'+num).fadeIn();
$('#external-'+random).fadeIn({'duration':600,'queue':false});
}else{
$('#cont-'+num).fadeOut();
}
}
This should be closer to what you're after (untested though).
Once you've got it working, you could look at simplifying it by using data-id="num" attributes on your HTML elements and accessing the id values with .data('id') in your js, then binding the tab buttons from within your DOM ready fn. It would look closer to this:
$(function() {
$('.tab').click(function (e) {
var num = $(this).data('id'),
$child = $('.child[data-id="' + num + '"]')
;
// ...
})
})
I think this changes to your function showCont(num) would do:
$('.content').fadeOut(300);
if( $('#cont-'+num).css('display')=='none' )
{
$('#cont-'+num).fadeIn();
var value= $('#cont-'+num+' div' ).first().attr("id").slice(-2);
$('#external-'+value).fadeIn();
}
else
{
$('#cont-'+num).fadeOut();
$('.external').fadeOut();
}

Best way to show all hidden divs in javascript

I have several hidden divs inside large div, they can be shown one by one or all at once
It looks like this:
<div class="maindiv">
Print "<a href=javascript:show()>Click here to show all</a>
Show/hide div1
<div id="div1" style="display:none;">.....</div>
Show/hide div2
<div id="div2" style="display:none;">.....</div>
....
</div>
showhide() function is ok showing/hiding given div, show() works too but like this:
function show(){
div1.style.display="block";
div2.style.display="block";
...
}
so if I'll have 100 divs I'll have to enter it there 100 times
so my question is, how can I find all hidden divs in div with class maindiv and show em other way than enumerate? Or is the way I do ok?
Try using a generic css class name that is defined similarly:
.hidden{
display:none;
}
Then all you have to do is select the elements that have that class and remove that class. Assuming you are using at least IE9 you can try:
var divs = document.getElementsByClassName("hidden");
for(var i = 0; i < divs.length; i++)
{
divs[i].className = ""; //assuming you only have that class set else you will need to do a search and replace
}
If you have to support earlier versions there are other methods that will work to gather all the divs you need such as document.getElementsByTagName("div")
LIVE DEMO
Try this:
JQuery
$('.maindiv div a').click(function(){
$(this).next().toggle();
});
$('#showAll').click(function(){
$('.maindiv div div').show();
});
HTML
<div class="maindiv">
Click here to show all
<div>
Show/hide div1
<div>.....</div>
Show/hide div2
<div>.....</div>
</div>
</div>
CSS
.maindiv div a{
display:block;
}
.maindiv div div{
display:none;
}
Please try with the below code snippet.
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//You can also write here if condition
divs[i].style.display = "block";
}
I think this can work
http://jsfiddle.net/rtu75/
function show() {
var divs = document.getElementsByClassName("maindiv");
var l = divs.length;
for( var i = 0; i < l; i++) {
divs[i].setAttribute("class", "show");
}
}
In your css
.show div {
display: block !important;
}
Added important since you have inline styles
Using jQuery, try
$("*").show();
or
$(parentElem).find("*").show();
or
$(":not(:visible)").show();
// This selects "*". Not I expected.
See w3 - css selectors, MDN - css pseudo classes, and jQuery $(), $().find(), $().filter() methods.
As I saw your code below, I saw it's almost work. You need to change id='div1' to class='hid' after that read my below step >> Go down
Show/hide div1
<div id="div1" style="display:none;">.....</div>
Here is my step, I am in same problem but now I can solve this because I read https://stackoverflow.com/a/24192071/10618118 then try to solve until done.
Read below,it's my code.It's work as I want.
in My Style for CSS be like this
<style>
.hid {}
</style>
Next is My Button to control it hidden or visible, Simple.
<button id="see" type="button" onclick="clickSee();">Show More ...</button>
Next step, look at my Javascript Code below,
I use JQuery 3.2.1 to change function in onclick of button.
when user want to hide or see more
just click Show More ... or ... Show less,
Actually it's the same button but user don't know.
If you didn't use JQuery yet and decide to use just copy
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
and paste in <head></head>
<script>
function clickSee() {
document.getElementById("see").innerHTML = "... Show Less";
var divs = document.getElementsByClassName("hid");
for (var i = 0; i < divs.length; i++){
divs[i].style.display = "block";
}
//I use JQuery
$("#see").attr("onclick", "clickHide()");
}
function clickHide() {
document.getElementById("see").innerHTML = "Show More ... ";
var divs = document.getElementsByClassName("hid");
for (var i = 0; i < divs.length; i++){
divs[i].style.display = "none";
}
//I use JQuery
$("#see").attr("onclick", "clickSee()");
}
</script>
If you have any issues just comment below, I will try to help because when done.
There are many way to make your idea work. but I see here is my basic way.
Feel free for new recommendation. Thank you.

Categories

Resources