My goal is to have the image switch once it's been clicked and back again to the original image once the second image has been clicked again. I hope that makes sense. I've been trying this for two days with no success. Any help would be appreciated.
/* global document */
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg')
}
}
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
<!-- <script>
var myHeading = document.querySelector("h1")
myHeading.textContent = 'Be Kind' ;
</script> -->
</body>
I have fixed your code. There is one error in your code i.e., you haven't mentioned the file extension whether its in .jpg or any other format in setAttribute. So let's say if your old-typewriter is in jpg format than this code will work if you have another format of image just replace jpg with that format and try to rerun this code.
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg')
}
}
I have edited complete code and you can replace your code with below code. It will work.
<!DOCTYPE html>
<html lang="en">
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
</body>
<script>
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg');
}
}
</script>
</html>
Holy-moly! So I took "Vipul's" suggestion of wrapping the code in script> and embedding the code in my HTML file which I wasn't doing before and voila. I want to thank all of you for the suggestions made. I hope I can return the favor one day.
Best,
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
<button>Change name</button>
<script src="scripts/myscripts.js"> </script>
<script>
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg');
}
}
var myHeading = document.querySelector("h1")
myHeading.textContent = 'Be Kind' ;
-->
This code should work:
index.html
<!doctype html>
<html>
<head>
<title>My Test Page</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<a onclick="switchImg()">
<img src="img1.png" id="img">
</a>
</body>
</html>
script.js
var imgSrc = document.getElementById("img").src
function switchImg() {
if(imgSrc == "img1.png") {
document.getElementById("img").src = "img2.png";
imgSrc = document.getElementById("img").src;
}
}
Just replace the names of the image files.
Related
I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
I'm working on a 3D interface with Babylonjs, so I need a canvas. Around that canvas I want to implement html elements (with Holy grail layout : nav to the left, main which is canvas at the middle and aside to the right) according to 2 modes : visualisation and edition.
I have a script to handle the canvas and play with babylonjs functions, and another one to manage the construction of the html according to the chosen mode.
As you can see in my code, I assign my html code to a variable, and append that variable to my holygrail main. However, I don't want my canvas to be recreated each time I change mode, so I implemented it directly in the HTML, it's constant.
My problem is : I want to append elements to my div #insertHere, but also to remove all the elements (excepted my canvas which has to remain) of this #insert div before appending new ones (else I would have several navs and asides).
Can anyone help me ?
Thank for your time !
Here's my construction script :
var content = "";
var construct = true;
var visualize = false;
function Create(){
content = "";
if(construct == true && visualize == false){
content += "<div id='1'> <p> hello</p></div><div><p>Insert a lot of html here</p></div>";
$("insertHere").append(content);
}
if(construct == false && visualize == true){
content += "<div id='not1'><p> Definitely not the same content as the construct one</p></div>";
$("insertHere").append(content);
}
}
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// INSERT THE SOLUTION TO CLEAR THE HTML HERE
CreationPage();
});
});
And here's my HTML (both are short representation of what I really have) :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
</head>
<body id="body" class="HolyGrail">
<header>
<link rel="stylesheet" type="text/css" href="style.css" media="all">
<link rel="stylesheet" href=".\bootstrap\css\bootstrap.css">
<link rel="stylesheet" href="justcontext.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" defer></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script style="text/javascript" src="scripts/construction.js" defer></script>
</header>
<div id='menuonglets' class='btn-group' role='group' aria-label='Basic example'>
<button type='button' class='btn btn-secondary' id='switchmode'>Mode Visu/ Mode Constru</button>
</div>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content'>
<canvas id='renderCanvas'></canvas>
</main>
<!-- Things are inserted here -->
</div>
</body>
</html>
You could use jQuery's filter() function to remove all elements but the canvas.
Here's a working example:
$("#btn_clear").on("click", function(e){
e.preventDefault();
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content' style="background: orange;">
<canvas id='renderCanvas'></canvas>
</main>
<p>I'm a paragraph</p>
<ul>
<li>Foo</li>
<li>bar</li>
</ul>
</div>
Remove all elements but the canvas
So:
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// Remove all elements, except for the canvas and its container.
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
CreationPage();
});
});
I am trying to display one of two images using a click button using random number generator by assigning each image to an if and else statement. I'm not sure where the problem is. Here is what I have:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9</title>
<link href="images/avatar.png" rel="shortcut icon" type="image/png">
<link href="css/stylesheet.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" type="text/javascript"></script>
<style type="text/css">
.auto-style1 {
text-align: center;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<header>
</header>
<aside>
</aside>
<div id="main">
<h1> Arrays and Coditional Statements</h1>
<h2 class="auto-style1">Flip a coin </h2>
<script>
function myFunction1() {
var result = doucment.getElementById("pic");
var x = Math.floor(Math.random() * 2);
console.log(x);
if (x == 0) {
document.getElementById("Coin").innerHTML = "Heads"
result.innerHTML="<img alt=\"the frontside of a coin\" src=\"images/heads.jpg\" />"; }
else {
document.getElementById("Coin").innerHTML = "Tails";
result.innerHTML= "<img alt=\"the backside of a coin\" src=\"images/tails.jpg\" />";
}
}
myFunction1();
</script>
<button type="button" onclick="myFunction1()" id="Coin">CLick ME</button>
<p id="pic"> </p>
</div>
<footer>
</footer>
</body>
</html>
You have a very simple typo. You wrote:
var result = doucment.getElementById("pic");
document is spelled wrong
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 months ago.
I am new to javascript programming.
When i try to run this code, the default image in html tags shows up.
I used the setAttribute function but it doesn't work. Please Help!
<!DOCTYPE HTML>
<html>
<head>
<title>Javascript</title>
<script type="text/javascript">
var foo = document.getElementById("image");
foo.setAttribute("src", "glasses.jpg");
</script>
</head>
<body>
<img src="awesomesite.gif" id="image" alt="Awesomesite">
<p id="intro">
Hello World
</p>
</body>
</html>
either move the script to the bottom of your page or add the following to your script
document.onload(function()
{
var foo = document.getElementById("image");
foo.setAttribute("src", "glasses.jpg");
});
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<img src="http://i.stack.imgur.com/xkF9Q.jpg" id="image" alt="Awesomesite">
<p id="intro">
Hello World
</p>
<script>
window.onload = function () {
var logo = document.getElementById('image');
logo.src = "http://www.w3schools.com/html/pic_mountain.jpg";
};
</script>
</body>
</html>
I am trying to create an image which is initially hidden - but reveals itself once the document has loaded completely via the JavaScript file.
$(document).ready(function () {
document.getElementById("theImage").style.visibility = "visible";
});
#theImage {
visibility:hidden;
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kami Nelson Bio </title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="KNelson-Styles.css" rel="stylesheet" type="text/css">
<script src="respond.min.js"></script>
<script src="KNelson_reveal.js"></script>
</head>
<body>
<div class="gridContainer clearfix">
<div id="theImage">
<img src="images/Kami-100.jpg" alt="Kami Nelson Image"/>
</div>
<div id="div1" class="fluid">
<h1>Bio for Kami Nelson</h1>
<p>Text</p>
</div>
</div>
</body>
</html>
Why is this not working?
Thank you in advance.
You should either include jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or use native window.onload() instead of $(document).ready()
window.onload=function () {
document.getElementById("theImage").style.visibility = "visible";
}
You are missing the jQuery library reference
You are not properly
using selecter to select image of id theImage.
theImage is supposed to be for the img tag.
JavaScript
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("#theImage").css('display':'block');
});
</script>
CSS
#theImage {
display: none;
}
HTML
<img id= "theImage" src="images/Kami-100.jpg" alt="Kami Nelson Image"/>
why don't you just draw the image when the window loads?
give your image an id i'll use "image" for this example.
<script>
window.onload = function ()
{
$('#image').css({"display":"block";});
}
</script>