Javascript function not triggering on button click - javascript

Here is the code:
<script>
function myFunction() {
var x = document.getElementById("myDIV");
var y = x.getElementsByClassName("child");
var i;
for (i = 0; i < y.length; i++) {
y[i].style.backgroundColor = "red";
}
}
</script>
<style>
div {
border: 1px solid black;
margin: 5px;
}
</style>
<div id="myDIV">
<p class="child">A p element with class="child" in a div.</p>
<p class="child">Another p element with class="child" in a div.</p>
<p>A p element in div with a <span class="child">span element with class="child"</span> inside of it.</p>
</div>
<p>Click the button to add a background color to all elements with class="child" inside the div element with id="myDIV".</p>
<button onclick="myFunction()">Try it</button>
https://jsfiddle.net/jmgrant15/3dcof7ox/14/
The "child" classes are supposed to turn red on the button click. Any thoughts why this isn't working?
Thanks!

Related

display different comand and result from getElementsByClassName() Method

i just wanna ask how to change or display the different color with "getElementsByClassName() Method" in javascript,so here i want to change the bacground color blue from class "ex",and color red form class "example",but it doesnt work.
<!DOCTYPE html>
<html>
<head>
<style>
.example {
border: 1px solid black;
padding 8px;
}
</style>
</head>
<body>
<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>
<p>Change the background color of all elements with class="example":</p>
<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="example"
</div>
<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="example".
</p>
<p>A <span class="example">span</span> element with class="example".</p>
<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
const collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "blue";
}
</script>
</body>
</html>
your code works fine but you had two variables with the name collection rename one of them
<!DOCTYPE html>
<html>
<head>
<style>
.example {
border: 1px solid black;
padding 8px;
}
</style>
</head>
<body>
<h1>The Document Object</h1>
<h2>The getElementsByClassName() Method</h2>
<p>Change the background color of all elements with class="example":</p>
<div class="example">
A div with class="example"
</div>
<br>
<div class="ex">
A div with class="example"
</div>
<p class="example">
A p element with class="example".
</p>
<p class="ex">
A p element with class="example".
</p>
<p>A <span class="example">span</span> element with class="example".</p>
<script>
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
const collection2 = document.getElementsByClassName("ex");
for (let i = 0; i < collection2.length; i++) {
collection2[i].style.backgroundColor = "blue";
}
</script>
</body>
</html>
What does "doesn't work" mean? Is ex blue, and example uncolored? Are none colored?
Try checking the output in console (Developer tools - F12). I am certain you will receive an error using your snippet, as you redefine the collection variable twice. Use let instead of const if you plan on using a solution which changes a variable's value after assignment. Alternatively, define another variable for your second for-loop.
Here's your snippet corrected if you're still not sure:
let collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
collection = document.getElementsByClassName("ex");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "blue";
}

How to Hide and then Show on Click Multiple Content Items by Default?

I have the following code. By default it shows, but I want to hide it by default.
Also, I'm unable to control both of the divs, only 1 of the show/hide toggles work, I want for them (but have been unsuccessful) both to work.
How can I hide by default and expand on click?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction()">Try it 2</button>
<div id="myDIV2">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
You are overwriting your x variable.
Assign myDIV2 to another variable like y and repeat the process.
Better would be to just assign the same class instead of id to the elements you want to hide and just toggle the class instead of trying to get each element by id.
https://ultimatecourses.com/blog/javascript-hasclass-addclass-removeclass-toggleclass
Just separate the function on the first and scond button
function myFunction_1() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction_2() {
var y = document.getElementById("myDIV2");
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

show/hide elements and switch between them js

I have two elements that are hidden. When button a is clicked, I would like div a to show. When button b is clicked, I would like div a to close and div b to show.
However, if button a is clicked a second time after being shown, I would like it to hide the div again. Same with button b.
Update:
I was able to get the buttons to toggle properly.
However, upon initial loading, I want them to be hidden, or not visible until the button is clicked.
The following is my current javascript
function openFamily(evt, famName) {
var i, x, y, tablinks;
x = document.getElementsByClassName("family");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
tablinks = document.getElementsByClassName("familytablink");
for (i = 0; i < x.length; i++)
document.getElementById(famName).style.display = "block";
}
I have a CSS element:
.container{
display: none;
}
HTML:
<div>
<div>
<button class="familytablink" onclick="openFamily(event,'zep')">Zephaniah</button>
<button class="familytablink" onclick="openFamily(event,'anna')">Anna</button>
</div>
<div id="zep" class="container mainp-2 family">
filler text
</div>
<div id="anna" class="container mainp-2 family">
filler text
</div>
</div>
Here's an exemple of how you can achieve that
var toggleDivById = function (id) {
var div = document.getElementById(id);
if (div.classList.contains('active')) {
return div.classList.remove('active');
}
div.classList.add('active');
}
var handleToggleClick = function (event) {
var targetId = event.target.dataset.target;
toggleDivById(targetId);
}
document.querySelectorAll('.toggle')
.forEach(function(toggle) {
toggle.addEventListener('click', handleToggleClick)
})
.toggable {
width: 50px;
height: 50px;
background-color: crimson;
border: 2px solid tomato;
visibility: hidden;
transition: all 100ms ease-out;
border-radius: 5px;
box-shadow: 1px 1px 2px indianred;
}
.toggable.active {
visibility: visible
}
<button data-target="a" class="toggle">A</button>
<button data-target="b" class="toggle">B</button>
<hr/>
<div id="a" class="toggable">A</div>
<div id="b" class="toggable">B</div>
In jQuery:
<script type="application/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("diva").show();
});
$("#button2").click(function(){
$("diva").hide();
$("divb").show();
});
});
</script>
In JS:
<script type="application/javascript">
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
You can use hide and show function in Jquery and use it when a button is clicked something like this :
like
$("selector").click(function(){
$("divid").hide();
$("divid").show();
})

Rearrange HTML Focused Tab's Row on button click

I'm porting a program from XAML/C# to HTML/CSS/JavaScript.
I have tabbed sections which rearrange the focused tab's row to the bottom when clicked. This is automatically performed by the TabControl in XAML.
XAML/C#
General Focused
Video Focused
HTML/CSS/JavaScript
How can I do the same with JavaScript?
I'm using this script https://www.w3schools.com/w3css/w3css_tabulators.asp
// Display Tab Section
function OpenTab(tabName) {
var i;
var x = document.getElementsByClassName("tabSection");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
}
.btnTab {
width: 33.33%;
display: block;
float: left;
background: #020f31;
color: #fff;
padding: 0.2em;
border-top: 1px solid #0080cb;
border-right: 1px solid #0080cb;
border-bottom: none;
border-left: 1px solid #0080cb;
cursor: pointer;
}
<!-- Tabs -->
<div id="sectionTabs">
<button class="btnTab" onclick="OpenTab('General')">General</button>
<button class="btnTab" onclick="OpenTab('Stream')">Stream</button>
<button class="btnTab" onclick="OpenTab('Display')">Display</button>
<button class="btnTab" onclick="OpenTab('Video')">Video</button>
<button class="btnTab" onclick="OpenTab('Audio')">Audio</button>
<button class="btnTab" onclick="OpenTab('Subtitles')">Subtitles</button>
</div>
<!-- Sections -->
<div id="General" class="tabSection">
General ...
</div>
<div id="Stream" class="tabSection" style="display:none">
Stream ...
</div>
<div id="Display" class="tabSection" style="display:none">
Display ...
</div>
<div id="Video" class="tabSection" style="display:none">
Video ...
</div>
<div id="Audio" class="tabSection" style="display:none">
Audio ...
</div>
<div id="Subtitles" class="tabSection" style="display:none">
Subtitles ...
</div>
Fiddle Link
Well if you can change markup a little bit like wrapping the first row and second row of the buttons on different div...
Also try to avoid inline javascript and use data-attributes here
Steps:
create a new array instance from iterable object y usinf Array.from
add a click event on all the buttons using addEventListener
hide all the elements containing tabSection class and also remove active class from all the buttons using for loop.
get the data-tab value from clicked button and set display:block to the respected tab and also add active class to the current button.
now for switching the .first and .second div up and down use insertBefore inside the if condition to compare the index of the clicked button
var x = document.getElementsByClassName("tabSection");
var y = document.getElementsByClassName("btnTab");;
var a = document.querySelector(".first");
var b = document.querySelector(".second")
var p = document.getElementById("sectionTabs");
Array.from(y).forEach(function(elem, index) {
elem.addEventListener("click", function() {
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
y[i].classList.remove("active");
}
var tab = this.getAttribute("data-tab");
document.getElementById(tab).style.display = "block";
this.classList.add("active");
if (index < 3) {
p.insertBefore(b, p.childNodes[0])
} else {
p.insertBefore(a, p.childNodes[0])
}
})
})
.btnTab {
width: 33.33%;
display: block;
float: left;
background: #020f31;
color: #fff;
padding: 0.2em;
border-top: 1px solid #0080cb;
border-right: 1px solid #0080cb;
border-bottom: none;
border-left: 1px solid #0080cb;
cursor: pointer;
outline: none;
}
.btnTab.active {
background: red;
}
<!-- Tabs -->
<div id="sectionTabs">
<div class="first">
<button class="btnTab" data-tab="General">General</button>
<button class="btnTab" data-tab="Stream">Stream</button>
<button class="btnTab" data-tab="Display">Display</button>
</div>
<div class="second">
<button class="btnTab active" data-tab="Video">Video</button>
<button class="btnTab" data-tab="Audio">Audio</button>
<button class="btnTab" data-tab="Subtitles">Subtitles</button>
</div>
</div>
<!-- Sections -->
<div id="General" class="tabSection" style="display:none">
General ...
</div>
<div id="Stream" class="tabSection" style="display:none">
Stream ...
</div>
<div id="Display" class="tabSection" style="display:none">
Display ...
</div>
<div id="Video" class="tabSection">
Video ...
</div>
<div id="Audio" class="tabSection" style="display:none">
Audio ...
</div>
<div id="Subtitles" class="tabSection" style="display:none">
Subtitles ...
</div>
Reference Link:
Array.from
forEach()
element.addEventListener
element.classList
element.style
node.insertBefore
This can be achieved by adding a bit more code to OpenTab().
First of all, to check whether a button in the top row or bottom row was pressed, you may add classes row1 to the first row of buttons and row2 to the second row. Then, you can check which button was pressed in OpenTab() by passing in this as an additional parameter: onclick="OpenTab(this, 'General').
With these changes to HTML, the javascript can be changed to change the button pressed into account. In the code below, each if statement checks that the current button is in a particular row with elem.classList.contains("rowX") and that the row is the top row with parent.firstElementChild.classList.contains("rowX"). It then loops through the number of tabs in the row (amount of tabs can vary) and places them in the beginning of the #sectionTabs div.
function OpenTab(elem, tabName) { // Note that `elem` is where `this` is passed
// Your original code
var i;
var x = document.getElementsByClassName("tabSection");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
// Additional code
row1_elem = document.getElementsByClassName("row1"); // initially top row
row2_elem = document.getElementsByClassName("row2"); // initially bottom row
parent = document.getElementById("sectionTabs");
// check that button in top row was clicked
if (elem.classList.contains("row1") == 1 && parent.firstElementChild.classList.contains("row1") == 1) {
// move elements from bottom row up
for (var j = 0; j < row2_elem.length; j++) {
parent.insertBefore(row2_elem[row2_elem.length-1], parent.firstChild);
}
// check that button in top row was clicked
} else if (elem.classList.contains("row2") == 1 && parent.firstElementChild.classList.contains("row2") == 1) {
// move elements from bottom row up
for (var j = 0; j < row1_elem.length; j++) {
parent.insertBefore(row1_elem[row1_elem.length-1], parent.firstChild);
}
}
}
A jsfiddle is also available:
https://jsfiddle.net/o687eLyb/
Note that you could also wrap the rows into separate divs with IDs rowX and use slightly different logic to check which row was pressed; however, this answer has the benefit that it keeps HTML structure the same.

Javascript - Using Events and Functions on elements within a div

Having difficulty with changing elements inside divs with events not understanding if i should use an for loop to go through div and make changes or put Events inside of divs and call them individually.
Also curious where i could use "this"
<html><head>
<script type='text/javascript'>
function changeBorder(){ //change all pics to red border
document.images.style.border="2px solid red";
}
function changeSize(){ //change pics in div1 to 100 onmouseover
pics = document.getElementById('div1');
for(i = 0; i < pics.length; i++)
{
pics[i].onmouseover.width = 100;
pics[i].onmouseover.height = 100;
}
}
function turnBlue(){ //paragraphs turn blue on doubleclick
alert("double click turn blue");
var paraBlue = document.getElementById.indexOf('p');
paraBlue.style.background="blue";
}
function yellowBack(){ //background on <p> to yellow onmouseover
var paraYell = document.getElementById.indexOf('p');
paraYell.style.background="yellow";
}
}
</script></head>
<body>
<div id="div1" onmouseover="changeSize()">
<img src="cat.jpg" id='im1' name='im1'/>
<img src="dog.jpg" id='im2' name='im2'/>
<img src="fish.jpg" id='im3' name='im3'/>
</div>
<div id="div2" ondblclick="turnBlue()">
<p id="p1">This is a paragraph</p>
<p id="p2">This is a paragraph</p>
<p id="p2">This is a paragraph</p>
</div>
<div id="div3" onmouseover="yellowBack()">
<p id="p4">This is a paragraph</p>
<p id="p5">This is a paragraph</p>
<img src="bird.jpg" id='im4' name='im4'/>
<img src="turtle.jpg" id='im5' name='im5'/>
</div>
</body>
</html>
too many problems to fix.
just one hint
function changeSize(){
var pics = document.querySelectorAll("#div1 img");
for(var i = 0; i < pics.length; i++){
pics[i].style.width = "100px";
pics[i].style.height = "100px";
}
}

Categories