Show multiple divs - javascript

so, I'm working on a project that has 2 tables in database that are related!
I need via JavaScript Hide and Show the divs containing the right information.
I got a main product Stone, and each Stone has 2 other Stone Types
So if I click on the img that has Stone1, I want to show Stone1.1, Stone1.2, etc and hide all the other StoneTypes.
This is what I got now on JS
jQuery('.Pedras').click(function(){
jQuery('.SubPedras').hide();
jQuery('#div'+$(this).attr('target')).show();
});
The problem here is that I only get the first div to show, eventhough I have 2 divs with the same Name example:
<div id="div{IdPedra}" class="SubPedras">
<div id="div{IdPedra}" class="SubPedras">
<div id="div{IdPedra}" class="SubPedras">
And {IdPedra} Is the id of the stone in the database, so I will get "div1" two or 3 times, etc.
Can anyone pls help me, I'm not able to find a suitable solution for my need.
Thank you!

You could use data-attributes to accomplish this. In your change my code to;
<div data-id="{IdPedra}" class="SubPedras">Stone 1.1</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 1.2</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 2.1</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 2.2</div>
You can access an element's data-attribute by using $(element).data("name"); this is equivalent to data-name. I also stored the Pedras
Loop through the SubPedras and check if they match the button where the parent category or value you wish to use as filter. Run the snippet, thanks!
(You could also store them to class attribute instead of data)
jQuery('.Pedras').click(function() {
// store button value to variable
var pedraValue = $(this).val();
// loop through the SubPedras
$(".SubPedras").each(function() {
// get the value from data attribute
if ($(this).data("id") == pedraValue) {
// if match show
$(this).show();
}
else{
// else hide
$(this).hide();
}
});
});
.SubPedras{
line-height:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="Stone1" class="SubPedras">Stone 1.1</div>
<div data-id="Stone1" class="SubPedras">Stone 1.2</div>
<div data-id="Stone2" class="SubPedras">Stone 2.1</div>
<div data-id="Stone2" class="SubPedras">Stone 2.2</div>
<button class="Pedras" value="Stone1">Stone 1</button>
<button class="Pedras" value="Stone2">Stone 2</button>

Related

JS: How to hide parent div with multiple nested divs, based on child div's content

Here's the code I'm looking at:
<div class="blotter_workshopitempublished blotter_entry">
<div class="blotter_author_block">
<div class="blotter_avatar_holder">
<a href="https://steamcommunity.com/profiles/steam_profile_id">
<div class="playerAvatar online">
<img src="https://steamcdn-a_medium.jpg" data-miniprofile="number">
</div>
</a>
</div>
<div>
nickname
</div>
<div>
added an item to their favorites </div>
</div>
I'd like to hide all occurrences of "blotter_workshopitempublished blotter_entry" based on "steam_profile_id" or "nickname" (one or the other, I don't care, but "id" would be better), which are inside nested divs.
I looked at several other similar questions but still need help; I'll use this inside a Tampermonkey script.
Thanks
Something like this should help:
const blotters = document.querySelectorAll('.blotter_workshopitempublished.blotter_entry');
blotters.forEach(blotter => {
const id = blotter.querySelector('a').href.split('/').pop();
if (id === "put whatever id you want to hide in here") {
blotter.style.display = "none";
}
});

QuerySelectorAll returns more than expected

<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub second">I don't want this</div>
</div>
Im trying to use QuerySelectorAll to return all "sub" divs nested inside "main" divs. Im currently using
document.querySelectorAll(".main .sub")
but this returns all divs that class name begins with "sub" so it also return divs with the class name "sub second" or "sub third" is it possible to just select divs thats class are "sub".
I also want to click on the results after using
document.querySelectorAll(".main .sub").click()
but this returns an error i think this is becasue
.click()
is only designed to work with one object at a time. Is it possible to select all divs with the class name "sub" and then click on them using something similar to
.click()
You can use this selector:
document.querySelectorAll(".main [class='sub']")
You can iterate over result items as follows:
var divs = document.querySelectorAll(".main [class='sub']");
[].forEach.call(divs, function(div) {
// do whatever
div.style.color = "red";
});
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>
<div class="main">
<p>I don't want this</p>
<div class="sub second">I don't want this</div>
</div>
Look at the accepted answer here: Fastest way to convert JavaScript NodeList to Array?
Array.prototype.slice.call(document.querySelectorAll(".main .sub")).forEach(function(el){
el.click();
})
EDIT 1 - Timeout
To timeout between each click, simple add a setTimeout call within a closed scope, reference the iteration and multiply with the desired delay:
Array.prototype.slice.call(document.querySelectorAll(".main .sub")).forEach(function (el, i) {
(function (a) {
setTimeout(function () {
el.click();
}, (10 * 1000) * a);
})(i);
})

Change text and image onclick

I am trying to figure out how to do this, but I can't get it.
It's supposed to be like a step by step-thing. When pressing the image, both the text and image will change. There are supposed to be 3 steps.
I have been trying a little bit js and php, but it haven't helped yet. Also CSS, but it's a little bit hard because it's 3, and not 2 steps. (I have been trying this e.g.: http://jsfiddle.net/eliranmal/2rwnz/)
<div id="forsideslides" class="row">
<div class="container">
<div id="forsideslides_tekst" class="col col-lg-6 col-sm-6"><div class="well">
<h1>Step 1</h1>
<p class id="forsideslides_innhold_tekst">Text 1 out of 3</p>
</div></div>
<div id="forsideslides_bilde" class="col col-lg-4 col-sm-4"><div class="well">
<img src="<?php bloginfo('stylesheet_directory'); ?>step1.png">
</div></div>
</div>
</div>
One of the codes I have been trying to use is the following:
$('.slider_innbokskontroll').click(function(){
var $this = $(this);
$this.toggleClass('slider_innbokskontroll');
if($this.hasClass('slider_innbokskontroll')){
$this.text('Les mer');
} else {
$this.text('Les enda mer');
}
});
But it was not what I have was looking for.
By pressing the image (see code below) it should change.
<div id="forsideslides_bilde" class="col col-lg-4 col-sm-4"><div class="well">
<img src="<?php bloginfo('stylesheet_directory'); ?>step1.png">
</div></div>
It should be changing like step1.png => step2.png (don't bother about the details with the link, I just made it simple to get it easier to understand)
The text below should also change:
<div id="forsideslides_tekst" class="col col-lg-6 col-sm-6"><div class="well">
<h1>Step 1</h1>
<p class id="forsideslides_innhold_tekst">Text 1 out of 3</p>
</div></div>
E.g like:
Step 1 -> Step 2
Text 1 out of 3 -> Text 2 out of 3
And so forth...
As I see it, it is relatively simple, but I have really no idea of what I am doing. Is there someone who could help me finding the solution? A short code I may understand would be fine.
Thank you.
Looks to me like you are not targeting the correct DOM element.
In your example jQuery code:
$('.slider_innbokskontroll').click(function(){
var $this = $(this);
$this.toggleClass('slider_innbokskontroll');
if($this.hasClass('slider_innbokskontroll')){
$this.text('Les mer');
} else {
$this.text('Les enda mer');
}
});
You are trying to change the $(this) object, instead of what you want above.
So instead do something like this:
$('.slider_innbokskontroll').click(function(){
$('#forsideslides_tekst h1').text('Step 2');
$('#forsideslides_tekst p').text('Text 2 out of 3');
$('#forsideslides_bilde img').attr('src', 'newimage.jpg');
});
where your on click will have the class slider_innbokskontroll
EDIT here is the jsfiddle: http://jsfiddle.net/2rwnz/204/
using your HTML code:
<div id="forsideslides" class="row">
<div class="container">
<div id="forsideslides_tekst" class="col col-lg-6 col-sm-6">
<div class="well">
<h1>Step 1</h1>
<p class id="forsideslides_innhold_tekst">Text 1 out of 3</p>
</div>
</div>
<div id="forsideslides_bilde" class="col col-lg-4 col-sm-4">
<div class="well">
<img src="http://placehold.it/350x150">
</div>
</div>
</div>
</div>
the jQuery:
$("#forsideslides_bilde img").click(function(){
if ($(this).attr('src') == 'http://placehold.it/350x150') {
$('#forsideslides_tekst h1').text('Step 2');
$('#forsideslides_innhold_tekst').text('Text 2 out of 3');
$(this).attr('src', 'http://placehold.it/350x200');
} else if($(this).attr('src') == 'http://placehold.it/350x200') {
$('#forsideslides_tekst h1').text('Step 3');
$('#forsideslides_innhold_tekst').text('Text 3 out of 3');
$(this).attr('src', 'http://placehold.it/350x300');
}
});
You can also use a global variable to detect which step, but just because I want to show you how you can detect which image i coded it that way.
You need to place the click event on your image first and then change the text...
Here is an example with jquery:
$('#forsideslides_bilde img').click(function() {
//Change text
$('#forsideslides_innhold_tekst').html('New text');
//Change image src
$('#forsideslides_bilde img').attr('src', 'newImageLocation.png');
});
You can try calling a JavaScript function when the image is clicked. In order to do that, you'll need to assign an onclick event listener to the image tag. In my example I'm using getElementsByName() so I'm giving each element a name tag as well...
<h1 name="change">Step 1</h1>
<p name="change">Step 1 of 3</p>
<img src="step1.png" name="change" onclick="nextStep()" />
Then you can use the Javascript code to get each one of the elements and change them accordingly. You should be able to add in the PHP method call for the image name without any issues.
<script language="javascript">
function nextStep() {
var changeElements = document.getElementsByName("steps");
changeElements[0].innerHTML = "Step 2"; // header tag
changeElements[1].innerHTML = "Text 2 out of 3"; // paragraph tag
changeElements[2].src = "<?php bloginfo('stylesheet_directory'); ?>step2.png"; // image tag
</script>
If the bloginfo('stylesheet_directory'); method call doesn't work within the JS code, you can assign that to a PHP variable instead and reference that variable in the JS code.

Toggle individual divs in a loop

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');
}
});

Check if n-th child exists, if not create and update

I have a div structure as
<div class="hours_logged">
<div class="time_item">
<div class="record_id"></div>
<div class="time_logged">0</div>
<div class="desc"></div>
</div>
</div>
I am adding new items dynamically. When I add new time I save that via AJAX call and update my DOM. The above is the DOM that I want to update. If user adds 2 new times I want to add another "time_item" DIV and populate values in that. I am already using jquery each function and I get the index number right for the DIV but how do I check like if index is 2 then
if(!$('.hours_logged').eq(index))
{
$('.hours_logged').append(' <div class="time_item">
<div class="record_id"></div>
<div class="time_logged">0</div>
<div class="desc"></div>
</div>');
}
try this:
if($('.hours_logged').length < 1)
{
$('.hours_logged').append(' <div class="time_item"><div class="record_id"></div><div class="time_logged">0</div><div class="desc"></div></div>');
}

Categories

Resources