Toggle individual divs in a loop - javascript

In rendering out data within HTML, which prints out a div down the page, for every row found in the database, I'm trying to find a way to allow each button that sits in each div to toggle the individual example when clicked (with a default of display:none upon loading the page) - something such as:
function toggle_div(id) {
var divelement = document.getElementById(id);
if(divelement.style.display == 'none')
divelement.style.display = 'block';
else
divelement.style.display = 'none';
}
An example of the final markup :
<div>
<div class="wordtitle">Word</div>
<div class="numbers">1</div>
<div class="definition">Definition</div>
<button class="button" id="show_example" onClick="toggle_div('example')">Show example</button>
<div class="example" id="example">Example 1</div>
</div>
<div>
<div class="wordtitle">Word</div>
<div class="numbers">2</div>
<div class="definition">Definition</div>
<button class="button" id="show_example" onClick="toggle_div('example')">Show example</button>
<div class="example" id="example">Example 2</div>
</div>
getElementById() only toggles the first div's example, and getElementsByClass() hasn't seemed to work so far - not too sure how to do this - any ideas much appreciated!

First rule, do not insert multiple elements with the same ID. IDs are meant to be unique.
What you need is to toggle the example near the button you clicked, and not any (or all) .example to be showed / hidden. To achieve this, considering you used the [jquery] tag in your question, you can either use a selector to get the nearest .example of your button, or use jQuery's built-in functions to get it (.siblings()).
I would personally put the onclick out of your markup, and bind this custom function in your javascript.
Another important thing : if javascript is disabled client-side, the user won't ever see your example, as they are hidden by default in CSS. One fix would be to hide it initially with JS (see the snippet for this).
Here's a demonstration of what I mean :
$('.example-trigger').click(function() {
//Use the current button which triggered the event
$(this)
//Find the sibling you want to toggle, of a specified class
.siblings('.example-label')
//Toggle (hide or show) accordingly to the previous display status of the element
.toggle();
});
//Encouraged : hide examples only if Javascript is enabled
//$('.example-label').hide();
.example-label {
display: none;
/* Discouraged : if javascript is disabled, user won't see a thing */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<button class="example-trigger">Toggle example 1</button>
<span class="example-label">Example 1</span>
</div>
<div>
<button class="example-trigger">Toggle example 2</button>
<span class="example-label">Example 2</span>
</div>
<div>
<button class="example-trigger">Toggle example 3</button>
<span class="example-label">Example 3</span>
</div>

As #Sean stated, you need the ID to be unique since that's the way you are getting your elements.
$words .= '<div class="wordtitle">' . $word .'</div>
<div class="numbers">' . $i . '</div>
<div class="definition">' . $definition . '</div>
<button class="button" id="show_example" onClick="toggle_div(\'example\''.$i.')">
show example</button>
<div class="example" id="example'.$i.'">' . $example . '</div>
<br/><br/>';
$i++;
#show_example will also be repeating so you will probably want to change that to a class.

Another answer, only because I had the answer ready and was called away before I could post it. So here it is.
Notice that for repeating elements, classes are used instead of IDs. They work just as well, and (as everyone else has already said), IDs must be unique.
jsFiddle demo
HTML:
<div class="def">
<div class="wordtitle">Aardvark</div>
<div class="numbers">1</div>
<div class="definition">Anteater</div>
<button class="button show_example">show example</button>
<div class="example" id="example">The aardvark pushed its lenghty snout into the anthill and used its long, sticky tongue to extract a few ants.</div>
</div>
<div class="def">
<div class="wordtitle">Anecdote</div>
<div class="numbers">2</div>
<div class="definition">Amusing Story</div>
<button class="button show_example">show example</button>
<div class="example" id="example">The man told an anecdote that left everyone laughing.</div>
</div>
jQuery:
var $this;
$('.show_example').click(function() {
$this = $(this);
if ( $this.hasClass('revealed') ){
$('.example').slideUp();
$('.show_example').removeClass('revealed');
}else{
$('.example').slideUp();
$('.show_example').removeClass('revealed');
$this.parent().find('.example').slideDown();
$this.addClass('revealed');
}
});

Related

How to show element only if other element contains something using jQuery?

My guess is what I want to achieve should be easy, but due to my lack of knowledge of front-end development, I cannot manage to solve issue. Have a page that works with AJAX-filters that users can select. Filters that are currently applied show up within <div> with id=current-filters.
HTML looks like this:
<div id="current-filters-box">
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<!-- here every single applied filter is displayed -->
</div>
</div>
</div>
Need to hide the the entire DIV current-filters-box in case no filter is applied.
The page uses a Javascript file, bundle.js which is massive, but contains the following line:
s=document.getElementById("current-filters")
Therefore tried the following if-statement to hide the DIV:
if(s.length<1)$('#current-filters-box').hide()
and
if(s=0)$('#current-filters-box').hide()
But this does not seem to have any effect. Can someone tell, what I did wrong?
Demo of page can be found here
EDIT: this is what the HTML looks like when filters are applied:
<div id="current-filters-box">
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<div class="badge-search-public">
<strong>Humanities & Languages</strong> <span class="x" data-property="disciplines" data-value="4" onclick="filter.removeFilter(this)">×</span>
</div>
<div class="badge-search-public">
<strong>January</strong> <span class="x" data-property="months" data-value="1" onclick="filter.removeFilter(this)">×</span>
</div>
</div>
</div>
Both of your conditions are incorrect or I would say they are not doing what you think they do.
s.length will always prints undefined so instead of s.length<1 you could use s.children.length
and the second one is not a condition rather it is an assignment
s==0 // condition
s=0 //assignment
the correct condition for your requirement would be
if(s.children.length<1){
I have assigned snippets for illustration.
Without filters
s = document.getElementById("current-filters")
console.log(s.children.length);
if (s.children.length < 1) {
$('#current-filters-box').hide(1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="current-filters-box">
filter box
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<!-- here every single applied filter is displayed -->
</div>
</div>
</div>
Without filters
s = document.getElementById("current-filters")
console.log(s.children.length);
if (s.children.length < 1) {
$('#current-filters-box').hide(1000)
}
<div id="current-filters-box">
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<div class="badge-search-public">
<strong>Humanities & Languages</strong> <span class="x" data-property="disciplines" data-value="4" onclick="filter.removeFilter(this)">×</span>
</div>
<div class="badge-search-public">
<strong>January</strong> <span class="x" data-property="months" data-value="1" onclick="filter.removeFilter(this)">×</span>
</div>
</div>
</div>
Try this .
if( $('#current-filters').is(':empty') ) {
$('#current-filters-box').hide()// or $('#current-filters-box').css("display","none")
}
You are performing an assignment, try..
if (s.children.length)
Using vanilla JavaScript, you can check if the current-filters div is empty or not and toggle the parent div current-filters-box like this:
s= document.getElementById("current-filters");
t= document.getElementById("current-filters-box");
if(s.children.length<1) {
t.style.display = 'none';
// t.style.visibility= 'hidden'; <<-- use this if you want the div to be hidden but maintain space
}
else {
t.style.display = 'block';
// t.style.visibility= 'visible'; <<-- use this if you used visibility in the if statement above
}
You can achieve this by adding your own variable which counts or maintains your applied filters, e.g.
var applied_filter_count = 0;
at every time filter is applied
applied_filter_count++;
if(applied_filter_count) {
$('#current-filters-box').show()
}
and at every time filter is removed
applied_filter_count--;
if(!applied_filter_count) {
$('#current-filters-box').hide()
}
and by default current-filters-box should be display:none

$('parent > child > childOfChild > ...').css('background-color','red)

HTML
<div class="galao">
<div class="informacoesGalao invisible">
<div class="tabelaInformacoes infoGalao" style="float:right; text-align:right">
<p class="nomeGalao">Produto A</p>
<p class="invisible volumeTotalGalao">1000</p>
<p class="invisible volumeAtualGalao">800</p>
</div>
</div>
<div class="desenhoGalao">
<div class="bordasGalao">
<div class="conteudoGalao"></div>
</div>
</div>
</div>
CSS
.conteudoGalao { background-color: blue }
I'm trying to select the <div class="galao"> and change the background color of the child <div class="conteudoGalao">.
When the user clicks into the <div class="galao"> this div turns into <div id="selectedGalao" class="galao">.
I've already tried $('#selectedGalao > conteudoGalao').css('background-color','red') but it doesn't even return a error or anything. Any idea of how I can make this work? Is there a specific jquery for this kind of "grandson div"?
The '>' css selector is for direct children. Since conteudoGalao is a grandchild it will not work. Simply use $('#selectedGalao .conteudoGalao').css('background-color','red') instead unless that's not specific enough, in which case I'll need more info as to why. IF that's how your markup will always work, and you do want to be extremely explicit in your selector, $('#selectedGalao > .desenhoGalao > .bordasGalao > .conteudoGalao').css('background-color','red'). Lastly, as CalvT said, you are also missing a period in front of 'conteudoGalao' to label it as a class.
You have an error in your jQuery. Try the following:
$('#selectedGalao .conteudoGalao').css('background-color','red')
You weren't specifying that conteudoGalao was a class, so do this by adding the . As the . was missing, jQuery was looking for an element called conteudoGalao
The > is for direct children, and conteudoGalao is not.

Handling an onclick event inside div tag using selenium java

How do I handle this div using Selenium?
<div onclick="Hover_Menu();Toggle_LevelToolMenu(this,event);"
class="edittop edit-one"></div>
I want to click on this and work with the menu that will be displayed. I believe I will be able to handle the menu that is display, however, I am not able to click on this div.
I tried using
driver.findElement(By.xpath("xpath")).click();
Thought I would use JavascriptExecutor but getElementbyId will not work since this is div and there is no ID associated
Example:
<div style="height:25px; width:55px;">
<div onmouseover="Hover_ToolBarMenu();" class="edit_box">
<div onclick="return Click_ToolBarMenu('Edit',1019, 9189707,event, this)" class="editopt edit">
Edit
</div>
<div onclick="Hover_LivesMenu();Toggle_ToolBarMenu(this,event);" class="editopt edit-dot dot"></div>
</div>
<div class="clr"></div>
<div style="display:none; position:relative;" class="qm_ques_level_menu">
<div onmouseover="Hover_LivesMenu();" onclick="return Click_ToolBarMenu('Delete',1019, 9189707,event, this)" class="menu_buttons img_ico del">
Delete
</div>
<div onmouseover="Hover_LivesMenu();" onclick="return Click_ToolBarMenu('Copy',1019, 9189707,event, this)" class="menu_buttons img_ico copy accor">
Copy <span class="arrowIcon">?</span>
</div>
<div onmouseover="Hover_LivesMenu();" onclick="return Click_ToolBarMenu('Move',1019, 9189707,event, this)" class="menu_buttons img_ico move accor">
Move <span class="arrowIcon">?</span>
</div>
<div onclick="return Click_ToolBarMenu('Deposit2QB',1019, 9189707,event, this)" class="menu_buttons img_ico qb">
Deposit to Bank
</div>
</div>
<div></div>
</div>
http://selenium-python.readthedocs.org/en/latest/locating-elements.html
can you not use CLASS_NAME
driver.find_elements(By.CLASS_NAME, 'edit-one')
or
driver.find_element_by_class_name('edit-one')
Find and click an item from 'onclick' partial value
How about something like this?
driver.find_element_by_css_selector("div[onclick*='Hover_Menu']")
Selenium: How to select nth button using the same class name
How about this one (would required the div to be in a static position)
var nth = 2;
var divs = driver.findElements(By.className("edit-one"));
var div = divs.get(nth);
div.click();
I was able to figure this out. I used jQuery for invoking the onclick function in this div
Below is the jQuery I used
var event = document.createEvent('Event');$('.editopt.edit-dot').get(0).onclick(event)
Thanks everyone who posted and helped me on this.

setAttribute use for Javascript functions

I have 3 nested divs..
<div onclick="highlight(this)">1
<div onclick="highlight(this)">2
<div onclick="highlight(this)">3
</div>
</div>
</div>
To stop event-bubbling, I want add a syntax to the divs - stopPropagation().
I've tried (for first div only here)
document.querySelectorAll("div")[0].setAttribute("onclick", "event.stopPropagation()");
But it's not working. What is the solution/alternative to this..??
I want the divs to be like..
<div onclick="highlight(this) event.stopPropagation()">1
As you need to stop propagation of event, it seems to make sense that the corresponding action is attached to event itself. Here's one possible way of using it:
HTML
<div id="outer" onclick="highlight(event, this)">
<div id="middle" onclick="highlight(event, this)">
<div id="inner" onclick="highlight(event, this)">
</div>
</div>
</div>
JS
function highlight(event, target) {
event.stopPropagation();
console.log( target.id + ' is clicked' );
}
Demo.

"Cut and Paste" - moving nodes in the DOM with Javascript

I have html code that looks roughly like this:
<div id="id1">
<div id="id2">
<p>some html</p>
<span>maybe some more</span>
</div>
<div id="id3">
<p>different text here</p>
<input type="text">
<span>maybe even a form item</span>
</div>
</div>
Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:
<div id="id1">
<div id="id3">...</div>
<div id="id2">...</div>
</div>
Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?
In this case, document.getElementById('id1').appendChild(document.getElementById('id2')); should do the trick.
More generally you can use insertBefore().
This function takes any node that is passed into it and wraps it with the tag given. In the example code snippet I wrapped a span tag with a section tag.
function wrap(node, tag) {
node.parentNode.insertBefore(document.createElement(tag), node);
node.previousElementSibling.appendChild(node);
}
function wrap(node, tag) {
node.parentNode.insertBefore(document.createElement(tag), node);
node.previousElementSibling.appendChild(node);
}
let toWrap = document.querySelector("#hi");
wrap(toWrap, "section");
console.log(document.querySelector("section > #hi"), " section wrapped element");
<span id="hi">hello there!</span>
You can use
insertAdjacentElement instead of appendChild to have more control about the position of element with respect to a target element.
Syntax: targetElement.insertAdjacentElement(position, element).
It has four position codes as:
'beforebegin': Before the targetElement itself.
'afterbegin': Just inside the targetElement, before its first child.
'beforeend': Just inside the targetElement, after its last child.
'afterend': After the targetElement itself.
it appears as:
//beforebegin
<p>
//afterbegin
foo
//beforeend
</p>
//afterend
In your case, you can write the code as:
document.getElementById('id2').insertAdjacentElement('beforebegin', document.getElementById('id3'));
Note that this way, you don't need reference the parent (container) element!
Also consider You have more elements than id2, id3, eg: id4, id5, id6. Now, if you want to reposition for example id5 after id2, its as simple as:
function changePosition() {
document.getElementById('id2').insertAdjacentElement('afterend', document.getElementById('id5'));
}
<div id='container'>
<div id='id1'>id1</div>
<div id='id2'><u>id2</u></div>
<div id='id3'>id3</div>
<div id='id4'>id4</div>
<div id='id5'><b>id5</b></div>
<div id='id6'>id6</div>
</div>
<p><input type='button' onclick="changePosition()" value="change position"></p>
In my opinion is worth adding that if you need just a visual change (the DOM will stay the same but I will change in the UI) you can use the CSS order property.
It is probably more efficient that working on the DOM like the other answers, althought again doesn't really change the DOM structure so of course is not a real answer to this question.
Example:
document.addEventListener("DOMContentLoaded", function () {
const btnEl = document.getElementById('btn-swap');
const elToSwap = document.getElementById('id2');
btnEl.addEventListener('click', e => {
elToSwap.classList.toggle("first");
});
});
.container {
display: flex;
flex-direction: column;
}
.first {
order: -1;
}
<div class="container">
<div id="id1">first DIV</div>
<div id="id2">second DIV</div>
</div>
<button id="btn-swap">swap divs</button>
Short
I just add button (at the bottom) and js to your html
id3.after(id2);
function swap() {
id3.after(id2);
}
<div id="id1">
<div id="id2">
<p>some html</p>
<span>maybe some more</span>
</div>
<div id="id3">
<p>different text here</p>
<input type="text">
<span>maybe even a form item</span>
</div>
</div>
<button onclick="swap()">swap</button>

Categories

Resources