Using Javascript, I want to toggle on and off between 2 images.
So far I am using a counter and then changing my innerHTML based off if the counter is even or odd for when the image is clicked
It works the first time i click the image by replacing the image already there, but after the first time it keeps on adding images instead.
How can i make it change the image after the second time rather than add images when I click?
<!DOCTYPE html>
<html>
<head>
<script>
var x = 0;
function myFunction() {
x++;
var div1 = document.getElementById('div1');
if (x % 2 != 0) {
var y = document.write('<img src="http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng" alt="sometext" onclick=myFunction()>');
div1.appendChild.innerHtml = y;
} else if (x % 2 == 0) {
var y = document.write('<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text" onclick=myFunction()>')
div1.appendChild.innerHTML = y;
}
}
</script>
</head>
<body>
<div id="div1" style="font-size:12px" onclick=myFunction()> <span onclick=myFunction()>
<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
</span>
</div>
</body>
</html>
If you are only trying to achieve the toggle effect something like this should work:
<!DOCTYPE html>
<html>
<head>
<script>
var x=0;
function myFunction(){
var div1=document.getElementById('div1');
if(x==0){
x=1;
document.getElementById("myimgid").src = "http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng";
}
else{
x=0;
document.getElementById("myimgid").src = "http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg";
}
}
</script>
</head>
<body>
<div id="div1" style="font-size:12px" onclick=myFunction()>
<span>
<img id="myimgid" src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
</span>
</div>
</body>
</html>
Related
I'm trying to use a single button to toggle between an image being visible and invisible. I want the first click to make the image appear, and the second to hide it again. I figured using a boolean would be the best way to do this, but I can't quite get it to work.
function myStats(){
counter = true;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
I realize this will obviously not work because I'm not toggling the boolean, but that's what I'm looking for help with.
Create a css class called hidden, then use classList.toggle(). When the button is clicked toggle the class on the image.
It can be done like this:
document.querySelector('button').addEventListener('click', myStats)
function myStats() {
document.getElementById('stat').classList.toggle('hidden')
}
.hidden { display: none; }
<center><button>Player 1</button></center>
<center><img id="stat" src="https://via.placeholder.com/150" class="hidden"></center>
I edited your snippet to put a toggle on there and made it so the function myStats() doesn't set counter = true everytime you click it. Seems to work fine. I also hoisted the declaration of the counter variable above that function declaration, since that's where your toggle should be, represented by counter = !counter.
let counter = true;
function myStats(){
counter = !counter;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
Boolean variable should be outside of the function so its value won't reset every time you called a function. Also you should toggle this boolean variable value from true to false and vise versa. Check out my solution. Hope this helps!
var isImageShouldBeVisible = true;
function toggleImageVisibility() {
isImageShouldBeVisible = !isImageShouldBeVisible;
if (isImageShouldBeVisible) {
document.getElementById('stat').style.display = 'block';
} else {
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:block;"/></center>
<button onclick="toggleImageVisibility()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
This is because counter remains same throughout the code. You need to add counter = !counter at end of you function. I would do it using ternary operators. There is need of Boolean just check the style.display
let elm = document.getElementById('stat');
function myStats(){
let {display} = elm.style;
elm.style.display = display === 'none' ? 'block' : 'none';
}
body{background-color: #A9A9A9;}
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
I'm trying to target an element through the use of two variables. I know how to do this for id's, but what I'm doing for classes doesn't seem to works. Does anyone have an idea what I'm doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
var colour = purple;
var number = 1;
function check() {
var x = document.getElementsByClassName(colour number);
x[0].innerHTML = "Hello World!";
}
</script>
</head>
<body>
<div>Username: </div>
<input id="test" type="text" onblur="check()">
<div class="1 purple">one</div>
<div class="2 red">two</div>
<div class="3 blue">three</div>
<div class="4 brown">four</div>
<div class="5 orange">five</div>
<div class="6 yellow">six</div>
<div class="7 white">seven</div>
</body>
</html>
Update
I've tried both options but neither seems to work. This is the updated script.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function check() {
var colour = purple;
var number = one;
//var x = document.getElementsByClassName(colour + ' ' + number);
var x = document.querySelector('.' + colour + '.' + number);
x[0].innerHTML = "Hello World!";
}
</script>
</head>
<body>
<input id="test" type="text" onblur="check()">
<div class="one purple">one</div>
<div class="two red">two</div>
<div class="three blue">three</div>
<div class="four brown">four</div>
<div class="five orange">five</div>
<div class="six yellow">six</div>
<div class="seven white">seven</div>
</body>
</html>
Also note, this is only a test script. Once I get it working, I'll add a lot more divs, one for each color/number combination, so selecting on one class will not work.
The expression colour number is not a valid expression.
To specify the class names you need a string with space separated class names, for example "purple 1". Concatenate the strings with a space between them:
var x = document.getElementsByClassName(colour + ' ' + number);
However, as both the colors and numbers are unique, you only need to look for one of them:
var x = document.getElementsByClassName(colour);
or:
var x = document.getElementsByClassName(number);
Note: Class names that are only digits may be problematic in some situations. It's recommended that a class name doesn't start with a digit.
You should construct a string:
var colour = 'purple';
var number = 1;
var x = document.querySelector('.'+colour+'.'+number);
I created a prompt box with a question. After answering, you receive the answer in a div created with JavaScript called id2. Now I am trying to place my id2 in front of id1 which is the parentNode. So it will show the answer above the first div id1. Can someone explain to me why it's not working?
<!DOCTYPE html>
<html>
<head>
<title>lab7</title>
<meta charset="utf-8" lang="en" name="my page" />
<style>
.class1 {
width: 100%;
height: 60px;
background-color: #BCC6CC;
}
</style>
<script type="text/javascript">
function loadQ() {
var firstdiv = document.createElement("div");
firstdiv.setAttribute("class", "class1");
firstdiv.setAttribute("id", "id1");
var jw = prompt("Which movie is number 1 Box Office 2015?","Jurassic World");
document.getElementById("id2").innerHTML ="" + jw + " Made $652,198,011 Total Gross Sales";
document.getElementById("id2").style.backgroundColor = "#786D5F";
var id1 = document.getElementByTagName("div")[0];
var parent1 = id1.parentNode();
var beforeME = document.getElementByTagName("id2");
parent1.insertBefore(id1, beforeME);
};
</script>
</head>
<body onload="loadQ()">
<div id="id1" class="class1">
<br>
<b>Top 2 Box Office Movie for 2015</b>
</div>
<div class="class2" id="id2">
</div>
</body>
</html>
There are at least two issues in your code:
document.getElementsByTagName needs an s (it returns multiple elements).
To get an object by id, you need to use document.getElementById.
I rewrote my code and made it more clear. So, each div id and class are define.
<script type="text/javascript">
function loadQ() {
var firstdiv = document.createElement("div");
firstdiv.setAttribute("class", "class1");
firstdiv.setAttribute("id", "id1");
firstdiv.style.backgroundColor = "#BCC6CC;";
document.getElementById('id1').innerHTML ="<h2 style='padding:20px;'>Top Box Office Movie 2015</h2>","<br><br>";
var seconddiv = document.createElement("div");
seconddiv.setAttribute("class", "class2");
seconddiv.setAttribute("id", "id2");
seconddiv.style.backgroundColor = "#786D5F";
var reper = document.getElementById('id1');
var parinte = reper.parentNode;
parinte.insertBefore(seconddiv, reper);
</script>
I'm attempting to navigate the DOM tree and retrieve html comments and display them in alert box. This is as far as I can get, my alert box keeps returning empty. How do I properly display a nodeList array? I've searched for hours and cant seem to find any info that makes sense.
<!DOCTYPE html>
<html>
<head>
<title>Hidden Comments</title>
<h1 style="text-align:center">Hidden Comments</h1>
<script>
function concatComs(){
var c=document.getElementById('body');
var array=[];
for(var i=0;c.childNodes.length<i;i++){
if(c.childNodes[i].nodeType==8) array[i]=c[i];
}
alert(array.toString());
}
</script>
</head>
<body id="body" style="text-align: center">
<!--you-->
<h2>Find the hidden comments!</h2>
<p>Look closely and you'll find them!</p><!--found-->
<input type="button" value="Go!" onClick="concatComs()"/>
<!--them-->
</body>
</html>
Your for loop should start like:
for(var i=0; i < c.childNodes.length; i++){
Additionally, you probably want to add c.childNodes[i] to your array.
function concatComs(){
var c = document.getElementById('body');
var array=[];
for(var i=0; i < c.childNodes.length; i++){
if(c.childNodes[i].nodeType==8) {
array.push(c.childNodes[i]);
}
}
var result = "";
for(i in array) {
result += array[i].textContent + " ";
}
document.write(result);
}
<div id="body" style="text-align: center">
<!--you-->
<h2>Find the hidden comments!</h2>
<p>Look closely and you'll find them!</p><!--found-->
<input type="button" value="Go!" onClick="concatComs()"/>
<!--them-->
</div>
You can select comment strings with a regex expression like this
match(/<!--.*?-->/g)
then you can trim the first 4 and last 3 letter for each string
substr(4,comments[i].length-7)
Final result is like this
<!DOCTYPE html>
<html>
<head>
<title>Hidden Comments</title>
<script>
function concatComs(){
var comments = document.body.innerHTML.match(/<!--.*?-->/g);
for (var i = 0; i < comments.length; i++)
comments[i] = comments[i].substr(4,comments[i].length-7);
alert(comments);
}
</script>
</head>
<body id="body" style="text-align: center">
<h1 style="text-align:center">Hidden Comments</h1>
<!--you-->
<h2>Find the hidden comments!</h2>
<p>Look closely and you'll find them!</p><!--found-->
<input type="button" value="Go!" onClick="concatComs()"/>
<!--them-->
</body>
</html>
btw you should place your h1 tag inside the body not head.
I'm using Javascript to show documents. First, I hide the content that is loaded. Then, if a user press a button, the text related to that button will become visible while hiding other texts.
Currently, my technique does not change the URL that shows in the address bar.
I would like to update the address bar when a user clicks on one of the content display buttons. For example:
address.com/value_of_button
And if a user enters:
adress.com/a_value
I want to change display of div associated with the value. How is this done?
You can always use a hash url, and set the url like this:
function setHash(var hash) {
window.location.hash = hash;
}
If you want to retrieve the hash in the link to update the page, you can use something like
function getHash() {
return window.location.hash;
}
And to update the page you can just simply use if statements like this:
if(getHash() == "#main") {
document.getElementById('content').innerHtml = "<p>Main content</p>";
}
I had already demonstrated this at some point in the last year with jQuery. It's possible to not use jQuery, of course, but I'll provide you with the demo I created. I'll port an example to regular Javascript as well.
<html>
<head>
<style type="text/css">
.content {
display: none;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#menu a').each(function(){
id = $(this).attr('href');
id = id.substring(id.lastIndexOf('/'));
id = id.substring(0,id.indexOf('.'));
$(this).attr('rel',id);
});
$('#home').show();
$('#menu a').click(function(e){
e.preventDefault();
$('.content').hide();
$('#'+$(this).attr('rel')).show();
location.hash = '#!/'+$(this).attr('rel');
return false;
});
});
</script>
</head>
<body>
<div id="menu">
Home -
One -
Two -
Three
</div>
<div id="home" class="content">
Home content.
</div>
<div id="one" class="content">
One content.
</div>
<div id="two" class="content">
Two content.
</div>
<div id="three" class="content">
Three content.
</div>
</body>
</html>
EDIT
DOM method as promised:
<html>
<head>
<style type="text/css">
.content {
display: none;
}
</style>
<script type="text/javascript">
window.onload = function(){
var links = document.getElementById('menu').getElementsByTagName('a'),
divs = document.getElementsByTagName('div'),
sections = [],
id = '';
for (var i = 0, size = divs.length; i < size; i++) {
if (divs[i].className.indexOf('content') != -1) {
sections.push(divs[i]);
}
}
for (var i = 0, size = links.length; i < size; i++) {
id = links[i].href;
id = id.substring(id.lastIndexOf('/') + 1);
id = id.substring(0,id.indexOf('.'));
links[i].rel = id;
links[i].onclick = function(e){
e.preventDefault();
for (var p = 0, sections_size = sections.length; p < sections_size; p++) {
sections[p].style.display = 'none';
}
document.getElementById(this.rel).style.display = 'block';
location.hash = '#!/' + this.rel;
return false;
}
}
document.getElementById('home').style.display = 'block';
};
</script>
</head>
<body>
<div id="menu">
Home -
One -
Two -
Three
</div>
<div id="home" class="content">
Home content.
</div>
<div id="one" class="content">
One content.
</div>
<div id="two" class="content">
Two content.
</div>
<div id="three" class="content">
Three content.
</div>
</body>
</html>