Target all elements in a list excepted clicked - javascript

I've been playing around with jQuery for ages but am finally trying to learn clean Vanilla JS.
I have a list of elements:
<div id="seriesList" class="seriesList rollable">
<div class="seriesLink" series="7">
<h3 class="name">Carrow Road</h3><p class="location">Norwich</p>
</div>
<div class="seriesLink" series="6">
<h3 class="name">White Heart Lane</h3><p class="location">London</p>
</div>
<div class="seriesLink" series="5">
<h3 class="name">Parc des Princes</h3><p class="location">Paris</p>
</div>
</div
I'm toggling a series of GSAP animation after clicking one of the .seriesLink. The first one i'm trying to achieve is making every elements exept the one clicked disapear.
i.e: I click on #carrow-road — #white-lane and #parc-des-princes would disapear.
I have this:
document.querySelectorAll(".seriesLink").forEach(item => {
item.addEventListener('click', event => {
// ForEach.Not ?
document.getElementById("seriesList").classList.toggle("rollable");
document.getElementById("home").classList.add("scrollable");
document.getElementById("rightPanel").classList.remove("scrollable");
tlOpenSeries.play();
})
})
The "class" system in Javascript is getting me lost, as I don't seem to be able to target my elements successfully.
I can't find a way to "reproduce" the each.not jquery provides. Any idea? Shall I add a class first to the clicked element and then target all elements without this "active" class? Is there a shortcut?
Many thanks

To accomplish that in vanilla JS you have to loop through the elements and check if the current element is not the clicked element.
Demo:
var divs = document.querySelectorAll(".seriesLink");
divs.forEach(item => {
item.addEventListener('click', event => {
for(var i = 0; i < divs.length; i++){
if(event.currentTarget != divs[i]){ // check here
divs[i].style.display = "none";
}
}
//.......
//.......
});
});
<div id="seriesList" class="seriesList rollable">
<div class="seriesLink" series="7">
<h3 class="name">Carrow Road</h3><p class="location">Norwich</p>
</div>
<div class="seriesLink" series="6">
<h3 class="name">White Heart Lane</h3><p class="location">London</p>
</div>
<div class="seriesLink" series="5">
<h3 class="name">Parc des Princes</h3><p class="location">Paris</p>
</div>
</div>

you can use filter:
const seriesLinks = document.querySelectorAll(".seriesLink");
seriesLinks.forEach(item => {
item.addEventListener('click', event => {
seriesLinks
.filter(i => i != item)
.forEach(i => // your logic... //);
//... rest of your code ... //
})
})
but anymay i think that a good practice is to split the code to simple little functions, for example hideAllExceptCurrent (allElemArray, currentElem), hideAllToggleCurrent (allElemArray, currentElem)

Related

js asynchronous problem just work first neighbor

I want click neighbor and change the main country. I click first card ok no problem. but other cards not working. This is my code:
function renderNeighbors(data) {
let html = "";
for (let country of data) {
html += `
<div class="col-2 mt-2">
<div class="card click-change">
<img src="${country.flags.png}" class="card-img-top">
<div class="card-body">
<h6 class="card-title neighborName">${country.name.common}</h6>
</div>
</div>
</div>
`;
}
document.querySelector("#neighbors").innerHTML = html;
document.querySelector(".click-change").addEventListener("click", () => {
let neighborName = document.querySelector(".neighborName").innerHTML;
getCountry(neighborName);
})
}
in photos I point red circle in my browser. that's only working card.
enter image description here
I want to click neighbors and change main country. but only work for first neighbor
here is my all html code https://pastebin.com/Sb9XWZhy
here, the problem you are setting your event only for the first chosen element that matches your locator .
querySelector return only the first element that matches.
you should add the event for all of your nodes that match the locator.
It's supposed that querySelectorAll returns an array that you can loop over it like that.
for (let element of document.querySelectorAll(".click-change")){
element.addEventListener("click", () => {
let neighborName =
element.children[1].children[0].innerHTML;//here I'm accessing the neighbourName from the element itself, I'm not sure about the indices but you can handle them yourself
getCountry(neighborName);
})
}

How do I loop through HTML DOM nodes?

I want to loop through a nested HTML DOM node, as shown below:
<div id="main">
<div class="nested-div-one">
<div class="nested-div-two">
<div class="nested-div-three">
</div>
</div>
</div>
<div class="nested-div-one">
<div class="nested-div-two">
<div class="nested-div-three">
</div>
</div>
</div>
</div>
How would I do this using Javascript to loop through every single one of the dividers?
I am guessing OP was not specific for DIV elements, here's a more dynamic approach:
So first you wanna get the first container, in your case it's:
var mainEl = document.getElementById('main');
Once you have that, each DOM element has a .children property with all child nodes. Since DOM is a tree object, you can also add a flag to achieve recursive behavior.
function visitChildren(el, visitor, recursive) {
for(var i = 0; i < el.children.length; i++) {
visitor(children[i]);
if(recursive)
visitChildren(children[i], visitor, recursive);
}
}
And now, let's say you want to change all div backgrounds to red:
visitChildren(mainEl, function(el) { el.style.background = 'red' });
You can use vanilla javascript for this
document.querySelectorAll('div').forEach(el => {
// el = div element
console.log(el);
});

Better (more performant) way to get specific DIVs?

I want to add a specific DIV to other DIVs of a defined class. Because the page changes regularly I do this on every DOM-Change. This happens quite often and there are a lot of DIVs (up to a few 1000) that meet the criteria.
(This is an extension so I cannot modifiy the source)
I do it this way:
$('.Qg').each(function() {
if ($(this).parent().find('.quickShare').length === 0)
{
$(this).before('<div class="quickShare">(some more html)<br/></div>');
}
});
That works but does not seem to be very performant, mainly because of the "each" - Loop
Is there a more elegant (and especially performant) way to get only those DIVs which's parent do not contain my DIV (something like $('.Qg').parent().without('quickShare').each(function(){}); (pseudocode)?
Update: To make it clearer a DOM-Example:
<div class="anOuterDiv>
<div class="Qg">something here</div>
</div>
<div class="anotherOuterDiv">
<div class="quickShare">already added</div>
<div class="Qg">something here</div>
</div>
I want to Add the "quickShare" div before the "Qg", but only if it does not exist. (So I want to get the upper Qg, but not the lower Qg)
Give all the parents of .Qg the class QgContainer, then do:
$(".QgContainer:not(:has(.quickShare)) > .Qg").each(function() {
...
});
Since you can't change the site, try:
$(".Qg").filter(function() {
return $(this).siblings(".quickShare").length == 0);
}).each(function() {
...
});
As you wanted better(more perfomant) then you could consider using pure Javascript.
HTML
<div class="anOuterDiv1">
<div class="Qg">something here</div>
</div>
<div class="anOuterDiv2">
<div class="quickShare">already added</div>
<div class="Qg">something here</div>
</div>
<div class="anOuterDiv3">
<div class="Qg">something here</div>
</div>
<div class="anOuterDiv4">
<div class="quickShare">already added</div>
<div class="Qg">something here</div>
</div>
Javascript
Array.prototype.forEach.call(document.getElementsByClassName('Qg'), function (Qg) {
var parentNode = Qg.parentNode,
quickShares = parentNode.getElementsByClassName('quickShare'),
newQuickShare;
if(!quickShares.length) {
newQuickShare = document.createElement('div');
newQuickShare.className = 'quickShare';
newQuickShare.textContent = 'Newly added';
parentNode.insertBefore(newQuickShare, Qg);
}
});
On jsFiddle
Next we should actually compare it against some jQuery, so we will use the accepted answer.
$(".Qg").filter(function() {
return $(this).siblings(".quickShare").length == 0;
}).each(function() {
$(this).before('<div class="quickShare">Newly added</div>');
});
On jsFiddle
And now lets see how they perform on jsPerf
You can filter each .Qg that's not preceded by a .quickShare sibling and then apply .before() on that:
$('.Qg')
.filter(function() {
var node = this.previousSibling; // start with previous sibling
while (node) {
if (node.className == 'quickShare') {
return false; // we found one
}
node = node.previousSibling; // keep trying with previous sibling
}
return true;
})
.before('<div class="quickShare">(some more html)<br/></div>');
This time it will definitely work:
$('div:only-child.Qg').each(function(){
$(this).before('<div class="quickShare">(some more html)<br/></div>');
});
Try this. This is very easy and readable and small and performant.
jsFiddle Demo http://jsfiddle.net/VS6mG/

When one is clicked, disable the other

So I have a mini slide menu in my website there is a menu you can choose what you want to read. There are points to click, when u clicked it the point get a red background.
But there is a problem.
When i click one point and then an other point the first clicked point have to lose his background.
Here is my HTML:
<div id="slide_button" onClick="clicked(this);"><dir class="button_1"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_2"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_3"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_4"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_5"></dir></div>
Here is my JS:
function clicked(slide_button) {
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
HERE IS AN EXAMPLE ON FIDDLE.
My "QUESTION IS" what i have to do to solve that?
What should I pay attention?
First you need to fix your HTML becaue your id values aren't unique. In fact, you don't even need id values, so you should use "slide_button" as a class. You can then use it to select all the buttons:
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
The CSS needs to be changed now so "slide_button" is a class selector, instead of an id selector:
.slide_button {
display: inline-block;
}
As for clearing the background, clear all of them before coloring the selected one red:
function clicked(slide_button) {
var buttons = document.getElementsByClassName('slide_button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].getElementsByTagName('dir')[0].style.backgroundColor = '';
}
slide_button.getElementsByTagName('dir')[0].style.backgroundColor = 'red';
}
jsfiddle
This uses just JavaScript with no JQuery, but if you are using JQuery, you might as well use it here. The code is a lot shorter and easier to follow.
Here's a JQuery version:
$(function() {
$('.slide_button').click(function() {
var $button = $(this);
$button.children(':first').css({ backgroundColor: 'red' });
$button.siblings().children(':first').css({ backgroundColor: '' });
});
});
Note: This registers a click-handler, so you can get rid of the "onclick" attirbutes.
jsfiddle
You have to select all other points and set their background to none.
Or remeber which point is selected and on select another just remove background on last and remeber current point, then set its background to red.
See fiddle: http://fiddle.jshell.net/399Dm/5/
At first id should be unique per element.
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
Second, you should store reference of clicked element if you want later remove background color, and instead of inline event handlers or binding all elements would be better if you use event delegation.
Demonstration
(function () {
"use strict";
// getting parent node of divs, due to bind click event. then
var ele = document.querySelector(".slide_button").parentNode,
prev = null; // store previous clicked element
ele.addEventListener("click", clickHandler); // event handler.
function clickHandler(e) {
var t = e.target; // get target of clicked element
// filter by target node name and class. edit: removed class checking
if (t.nodeName.toLowerCase() === "dir") {
// checking value of prev !== null and it's not same element.
if (prev && prev !== t) {
prev.style.backgroundColor = "";
}
prev = t; // store clicked element
t.style.backgroundColor = "red";
}
}
}());
I have fixed the fiddle so that it works hopefully as you plan.
http://jsfiddle.net/399Dm/8/ There you go!
var forEach = function(ctn, callback){
return Array.prototype.forEach.call(ctn, callback);
}
function clear(element, index, array) {
element.getElementsByTagName("dir")[0].style.backgroundColor="";
}
function clicked(slide_button) {
forEach(document.getElementsByClassName("slide_button"), clear);
//.style.backgroundColor="";
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
I had a slightly different method than #atlavis but a similar result.
http://fiddle.jshell.net/2AGJQ/
JSFIDDLE DEMO
jQuery
$('.slide_button').click(function(){
$('.slide_button dir').css("background-color", "inherit");
$(this).find('dir').css("background-color", "red");
});
HTML - Your markup is invalid because you have duplicate ids. Make them classes as below instead.
<div class="slide_button" >
<dir class="button_1"></dir>
</div>
<div class="slide_button">
<dir class="button_2"></dir>
</div>
<div class="slide_button">
<dir class="button_3"></dir>
</div>
<div class="slide_button">
<dir class="button_4"></dir>
</div>
<div class="slide_button">
<dir class="button_5"></dir>
</div>
CSS change
.slide_button {
display: inline-block;
}
If you can look at the following jsfiddle, I used jQuery to get what you want.

jQuery matching a single class against predefined list where element has multiple classes

I am trying to figure out if there is a way around doing .hasClass() multiple times to see if the active element I am working with has one of currently four specific classes, I am also trying to figure out the most optimized way to do this while the element(s) that are acting as the trigger (or the active element) has multiple classes in it mostly for styling purposes.
Example of the HTML:
<div class="form_row">
<div class="primary_row">1</div>
</div>
<div class="form_row">
<div class="primary_row subexists">1</div>
<div class="primary_row_sub">1a</div>
</div>
<div class="form_row">
<div class="primary_row subexists">1</div>
<div class="primary_row_sub subexists">1a</div>
<div class="secondary_row">2</div>
</div>
<div class="form_row">
<div class="primary_row subexists">1</div>
<div class="primary_row_sub subexists">1a</div>
<div class="secondary_row subexists">2</div>
<div class="secondary_row_sub">2a</div>
</div>
I am in the progress of currently building it up, so this is still a rough draft, but its safe to assume more classes will exist on various elements per the need. The Four main classes I am worried about are primary_row, primary_row_sub, secondary_row, secondary_row_sub. I am building a click handler like:
$('.form_row > div').click(function()
{
//code
});
in this click handler I want to be able to detect if the element clicked is one of the four mentioned above. Where if it is, I want to do something based on which. So determining which class is of the element clicked, rather than building four click handlers one for each type. I am hoping I can keep it optimized and contained to a single handler. Any ideas?
One option:
var classMap = {"one": function () { alert("one");},
"two": function () { alert("two");},
"three": function () { alert("three");}
}
, classes = "";
$('div').click(function (e) {
classes = this.className.split(" ");
for (key in classMap) {
if ($.inArray(key, classes) !== -1) {
classMap[key]();
}
}
});
http://jsfiddle.net/wp9X7/5/
if ($(this).is(".primary_row")) {
...
} elseif ($(this).is(".primary_row_sub")) {
...
} and so on

Categories