How to correctly target by class name? - javascript

I am trying to practice some things on JS, I want to toggle a number of divs on click to change their color but I can't seem to target correctly the first one. It was fine when I did it by tag name but by class it doesnt seem to work. What am I doing wrong? Thanks!
EDIT. This is what my code looks like after your corrections.
<body>
<div class="container">
<div class="one">
</div>
<div class="two">
</div>
<div class="three">
</div>
<div class="four">
</div>
</div>
<script src="script.js"></script>
</body>
let boxOne = document.getElementsByClassName("one")[0]
boxOne.onclick = function() {
alert("Clicked!")
}

I'm going to add that its better to assign an id and use getElementById if the selector is only used by one element.
let boxOne = document.getElementById("one");
let allBoxes = document.getElementsByClassName("square");
boxOne.onclick = function() {
alert("Clicked via ID");
}
const arr = [1, 2, 3];
arr.forEach(i => {
allBoxes[i].onclick = function() {
alert("Clicked via Class");
}
})
.square {
width: 100px;
height: 100px;
background: blue;
margin: 20px;
font-size: 50px;
color: white;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
cursor: pointer;
}
<body>
<div class="container">
<div class="square" id="one">
1
</div>
<div class="square" id="two">
2
</div>
<div class="square" id="three">
3
</div>
<div class="square" id="four">
4
</div>
</div>
</body>

With this line:document.getElementsByClassName(".one")[0]
you are already targeting the div, so change out this:
boxOne[0].onclick =
to this:
boxOne.onclick =

document.
getElementsByClassName returns array of elements with that className (without dot)
querySelector is used for css selectors (eg. ".one", "div.one")
querySelectorAll like 2. but returns array

let boxOne = document.getElementsByClassName("one")[0]
boxOne.onclick = function() {
alert("Clicked!")
}
div {
width: 100px;
height: 100px;
margin: 30px;
background: blue
}
<body>
<div class="container">
<div class="one">
</div>
<div class="two">
</div>
<div class="three">
</div>
<div class="four">
</div>
</div>
<script src="script.js"></script>
</body>

Related

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

Modify DOM based on amount of divs after specific class

Is there any way to modify DOM based on amount div after specific class?
For example, if I have a div with a class called row and after that I have 4 div elements. Is there a way to change these 4 div element class depending on how many div elements there are?
Code:
<div class="row">
<div class="col-1-of-4">
some content
</div>
<div class="col-1-of-4">
some content
</div>
<div class="col-1-of-4">
some content
</div>
<div class="col-1-of-4">
some content
</div>
</div>
Another example I have a div class row again, but this time I want 3 div elements after that, then I would want these div elements to have a class called col-1-of-3, not col-1-of-4. If I would have just 2 div elements after that then class col-1-of-2 and if just one div element then no class at all.:
Code:
<div class="row">
<div class="col-1-of-3">
some content
</div>
<div class="col-1-of-3">
some content
</div>
<div class="col-1-of-3">
some content
</div>
</div>
Also these div elements with classes called col-1-of-4, col-1-of-3 and col-1-of-2 have their own div elements inside them, but they should stay like they were.
Is it possible to achieve with JavaScript or PHP?
You would need to write conditional blocks to handle this if I'm understanding you correctly (wanting a JS or PHP solution).
Note: It goes without saying that a similar solution can be completed with a CSS-only approach, as outlined here: Can CSS detect the number of children an element has?
Here's an example (using jQuery) with 3 sets of row's, with varying children (2, 3, 4):
$(function() {
var $rows = $(".row");
$rows.each(function() {
$row = $(this);
var $children = $(">div", $row),
total = $children.size();
$children.addClass("col-1-of-" + total);
});
});
.row {
border: 1px solid #000;
margin: 10px;
}
.row > div {
margin: 10px;
}
.row .col-1-of-2 {
border: 1px solid #f00;
}
.row .col-1-of-3 {
border: 1px solid #0f0;
}
.row .col-1-of-4 {
border: 1px solid #00f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div>
some content
</div>
<div>
some content
</div>
</div>
<div class="row">
<div>
some content
</div>
<div>
some content
</div>
<div>
some content
</div>
</div>
<div class="row">
<div>
some content
</div>
<div>
some content
</div>
<div>
some content
</div>
<div>
some content
</div>
</div>
When you run the snippet, you must inspect the elements. I've added borders so you can see the difference.
Theres a number of ways to achieve this. I'd maybe add another class name so you can easily identify groups of divs, and differentiate between parent and child divs. Does this help you get where you're going? Basically find the number of children in a row and then concatenate that number into the class name.
var x = document.getElementsByClassName('row')[0].childElementCount
var element = document.getElementsByClassName('row')[0];
element.classList.add(`col-1-of-${x}`);
.row {
width: 100%;
display:flex;
flex-grow: 1;
margin-bottom: 2px;
}
.col {
float:left;
background: rgba(255,0,0,.2);
text-align: center;
margin-right: 2px;
}
.col:first-child:nth-last-child(1),
.col:first-child:nth-last-child(1) ~ .col{
width: calc(100% / 1);
}
.col:first-child:nth-last-child(2),
.col:first-child:nth-last-child(2) ~ .col{
width: calc(100% / 2);
}
.col:first-child:nth-last-child(3),
.col:first-child:nth-last-child(3) ~ .col{
width: calc(100% / 3);
}
.col:first-child:nth-last-child(4),
.col:first-child:nth-last-child(4) ~ .col{
width: calc(100% / 4);
}
.col:first-child:nth-last-child(5),
.col:first-child:nth-last-child(5) ~ .col{
width: calc(100% / 5);
}
<div class="row">
<div class="col">1</div>
</div>
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
</div>
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
</div>
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
</div>
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
<div class="col">5</div>
</div>
so this is with float, can be used in a sass/scss mixin to create code automagically. there should be also a flex solution but i dont have it at hand at the moment

jQuery closest() appears to find parent id when there is none

I have an event listener for when the user clicks in the window. I want to see if the clicked element has any parent element with a certain id. I use the jQuery closest() function for that. But it always returns true.
Here is a fiddle that demonstrates my code.
There must be some major error, because if I change the id from if($(event.target).closest('#activatemenu'))
into any other id
if($(event.target).closest('#rrrrrrr'))
it still returns true.
Code in fiddle:
$(function() {
$(document).click(function(event) {
if($(event.target).closest('#activatemenu')) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activatemenu</p>');
}else{
$('.wrap p').remove();
}
});
});
.stuff{
width:300px;
height:150px;
border:red 2px solid;
}
.otherstuff{
width:400px;
height:400px;
background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activatemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
Closest always returns a jQuery object which resolves to truthy. You need to check the length of the object.
$(event.target).closest('#rrrrrrr').length
Or, use
$(function() {
$(document).click(function(event) {
if ($(event.target).closest('#activemenu').length) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activemenu</p>');
} else {
$('.wrap p').remove();
}
});
});
.stuff {
width: 300px;
height: 150px;
border: red 2px solid;
}
.otherstuff {
width: 400px;
height: 400px;
background: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
$(event.target).closest('#activatemenu') will always return an object so if condition will always be true, better check for $(event.target).closest('#activatemenu').length
$(function() {
$(document).click(function(event) {
if($(event.target).closest('#activemenu').length) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activemenu</p>');
}else{
$('.wrap p').remove();
}
});
});
.stuff{
width:300px;
height:150px;
border:red 2px solid;
}
.otherstuff{
width:400px;
height:400px;
background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
You have two problems with your code.
First, you need to search for the closest activemenu not activatemenu. activatemenu does not exist in your code.
Second, jQuery will always return an array so you need to check the length to see whether the element was found as a non-empty array will always return true.
See below for a working example:
$(function() {
$(document).click(function(evt) {
if($(evt.target).closest('#activemenu').length) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activemenu</p>');
} else {
$('.wrap p').remove();
}
});
});
.stuff {
width: 300px;
height: 150px;
border: red 2px solid;
}
.otherstuff {
width: 400px;
height: 400px;
background: purple;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<div class="wrap">
<div id="activemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>

Getting divs next to each other when clicking on a button / JQuery

i am making a kind of storyboard where you can add and remove frames but i need to set divs next to each other, the code i now have it places the div's beneath each other. I want to make it with a loop
Here is my code:
HTML
<div id="storyboard">
<div id="container">
<div class="frame">
<div class="frame__outer">
<div class="frame__inner"></div>
<div class="frame__content"></div>
<div type="button" value="fade_in" class="add__button"> + </div>
</div>
</div>
</div>
</div>
JS
_this.addClickFunction = function() {
var i = 0;
$('.add__button').click(function() {
$('.frame').after('<div id="container'+(i++)+'"></div> <div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content"></div></div>');
});
};
Use append() instead of after() function. This should work:
_this.addClickFunction = function() {
var i = 0;
$('.add__button').click(function() {
$('.frame').append('<div id="container'+(i++)+'"></div> <div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content"></div></div>');
});
};
This works for keeping one .frame element and adding multiple divs to it of the structure:
<div class="container[i]">
<div class="frame__outer">
<div class="frame__inner"></div>
<div class="frame__content"></div>
</div>
</div>
If you want to arrange elements side by side which normaly are block elements and thus are positioned underneath eachother by default use either css floats or css flexbox.
https://css-tricks.com/all-about-floats/
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
i need to set divs next to each other
Try this example to add new story container to all current .container
var i = 1;
$('.add__button').click(function() {
i++;
$(".container").each(function(x) {
$(this).after('<div id="container' + x + '_' + i + '" class="container"><div class="frame"><div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content">story ' + i + '</div></div></div></div>');
});
});
.frame__outer {
padding: 20px;
background: #222;
color: white;
border-bottom: solid 3px green;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="storyboard">
<input type='button' value='add story' class="add__button" />
<div id="container" class='container'>
<div class="frame">
<div class="frame__outer">
<div class="frame__inner"></div>
<div class="frame__content">story 1</div>
</div>
</div>
</div>
</div>

How to hide div when it's already open?

I couldn't think of any better title, so I will try to explain my question here as clear as possible. I'm quite a newbie in JQuery so this is probably a very easy question.
I have some divs with a button on it. When you click the button, another div should pop-up.
My question is: How can I make the div, which is already open, close when clicking on another button?
I made a fiddle with some example code: http://jsfiddle.net/zuvjx775/1/
And the example code here:
HTML:
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2"value='click!' />
</div>
<div class="show_2">
</div>
</div>
JQuery:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
$('.show_'+id).show();
});
When show_1 for example is visible, and I click on the button in div2, I want show_2 to come up, which it does, but show_1 to dissapear.
Can someone point me in the right direction?
You can hide all divs that their class starts with 'show' before show the one you want. For example:
$('.showDiv').on('click', function() {
var id = $(this).attr('id');
$("div[class^='show']").hide();//find div class starts with 'show' and hide them
$('.show_' + id).show();
});
.test {
border: 1px solid black;
height: 100px;
width: 450px;
float: left;
}
.show_1 {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
display: none;
}
.show_2 {
width: 50px;
height: 50px;
background-color: green;
float: left;
display: none;
}
.wrapper {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2" value='click!' />
</div>
<div class="show_2">
</div>
</div>
Is the structure of the document fixed?
is so... I guess the easiest way of doing this is to just do the following:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
if(id == 1){
$('.show_1').show();
$('.show_2').hide();
}else{
$('.show_2').show();
$('.show_1').hide();
}
})

Categories