Simple javascript change image not working - javascript

I want to change an image's src on click of a link. I got a javascript snippet and tried to integrate it but it doesn't work.Im
Here's my HTML:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="styles/script.js"></script>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
</body>
</html>
Here is my script.js:
var imageId = document.getElementById("bgimage");
function changeImage() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}

This issue is occurring because the script appears in the html before the <img> element. Therefore, the code tries to find the img element, but it can't because the js code executes before the rest of the html is parsed. Correct it by putting the js include tag just before </body>:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
<script src="styles/script.js"></script>
</body>
</html>
Or, you might want to use DOMContentLoaded to wait until the html has been parsed. Change the js to this, in that case:
var changeImage;
document.addEventListener('DOMContentLoaded',function(){
var imageId = document.getElementById("bgimage");
changeImage=function() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
},false);
Or you could call document.getElementById() every time changeImage is called

You must place your script just before </body>, or run it at onload.
If not, you run
var imageId = document.getElementById("bgimage");
before loading the image to the DOM, so imageId is null.
Anyway, you could improve your function to
var images = ["images/1.jpg", "images/2.jpg" /*, ... */];
function changeImage() {
imageId.src = images[(images.indexOf(imageId.src)+1) % images.length];
}

Related

html is not rendering my image and the source is correct

I am trying to make the image "id = image" appear but it wont show up. I have done it with a simpler version where all i had was the body and the image tag and it worked but it wont appear in this format
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="index.js"></script>
<title>Text To Gif</title>
<script src="//www.WebRTC-Experiment.com/RecordRTC.js"></script>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
function onClicked() {
socket.emit('record');
socket.on('message', function(data){
document.getElementById('transcript').innerHTML = data; });
var downloadButton = document.getElementById("search_button");
var counter = 11;
id = setInterval(function() {
counter--;
if(counter < 0) {
downloadButton.innerHTML = "Record";
document.getElementById('transcript').innerHTML = "";
clearInterval(id);
} else {
downloadButton.innerHTML = counter.toString();
}
}, 1000);
}
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://fonts.googleapis.com/cssfamily=Montserrat">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Lato", sans-serif}
.w3-bar,h1,button {font-family: "Montserrat", sans-serif}
.fa-anchor,.fa-coffee {font-size:200px}
</style>
<body>
<!-- Header -->
<div class="w3-container w3-red w3-center" style="padding:250px 16px">
<h1 class="w3-margin-small w3-jumbo">Click Below To Start</h1>
<button type="button" onclick="onClicked();" id="search_button" class="w3-button w3-black w3-padding-large w3-large w3-margin-top">Record</button>
<p id="transcript"></p>
<img src="C:/Users/vlisn/Documents/speechapi/texttogif/images/cokelogo.png"
id="image" width="110" height="107">
</div>
</body>
</html>
can you help me out? i think it has to do with the code around it not the image tag
I've edited your question because oh my god my eyes.
Now that I've done it, I see tons of flaws in your HTML. You have <meta> tags that are outside your <head> and they can't/shouldn't be. You are also loading <link> outside of it.
Now partially, the issue with rendering could be because you are using a flat out path with C:/Users/vslin...... Try creating a folder called images in the same level as your HTML file and copying the image inside there, and then just using something like src="images/cokelogo.png".
It should be working, so the only reasons that seem viable are that you have the HTML file broken with the <link> and metas outside the <head>, or because of the absolute file pathing instead of relative one.
Edit: As per #LisaJoseph 's comment, it really seems like the absolute path is the issue here. Running on a server, you can't do src="C:/User/...." simply because those folders do not exist in your server. What you need to do is relative paths, as such:
- ServerFolder
|- index.html
|- images/
|- cokelogo.png
And with this structure, you can then just do
<img src="images/cokelogo.png">
And the server will find it.

Inserting js into iframe not working as expected

I am trying to copy jsfiddle's feature on my web page - a user can submit js on a page and it will be executed within an iframe. I ran some test code in jsfiddle and on my page. It works in jsfiddle, but not on my page. Any help is appreciated!
My page renders the css and html, but the js is not executing (the div background should be blue):
Here is the html in the iframe of the fiddle (which works):
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
.test { display:inline-flex; padding:40px; background-color:#cccccc }
</style>
<title></title>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
</script>
</head>
<body>
<div class="test" style="background-color: rgb(21, 160, 249);">test</div>
</body></html>
Here is the output to my web page:
<html><head><style>
.test { display:inline-flex; padding:40px; background-color:#cccccc }
</style><script type="text/javascript">//<![CDATA[
window.onload=function(){
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
</script></head><body><div class="test">test</div></body></html>
The code that inserts the html, css, and js into the iframe:
$(document).ready(function() {
var codeContainer = document.querySelector('.executedCode'); //submitted code passed as values in attributes to hidden div on the page in node/express environment
var html = codeContainer.getAttribute('html');
var css = codeContainer.getAttribute('css');
var js = codeContainer.getAttribute('js');
var sandbox = $('.sandboxed');
sandbox.ready(function() {
var htmlContainer = document.createElement('div');
var cssContainer = document.createElement('style');
var jsContainer = document.createElement('script');
jsContainer.setAttribute('type', 'text/javascript');
var head = sandbox.contents().find('head');
var body = sandbox.contents().find('body');
$(head).append(cssContainer);
$(head).append(jsContainer);
$(html).append(htmlContainer);
$(cssContainer).append('\n\t'+css+'\n');
$(jsContainer).text('//<![CDATA[\nwindow.onload=function(){\n'+js+'\n}//]]>\n');
body.prepend(html);
});
});
window.onload seems to be the breaking point:
I ran a test by simply inserting an alert. Here's what worked and what didn't.
$(jsContainer).text("alert('hi')"); //--works
$(jsContainer).text('//<![CDATA[\nalert("hi");\n//]]>\n'); //-- works
$(jsContainer).text('window.onload=function(){\nalert("hi");\n}\n'); //-- doesn't work
The execution occurs on the line $(jsContainer).text(js) but the html isn't inserted yet.
You just need to move the line $(jsContainer).text(js) after the body.prepend(html) (without the onload event).

document.querySelector(...) is null error

For image upload in a cakephp project I used java-script.I added this js file in app\View\Layouts default.ctp
js code
document.querySelector('input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
if (files[i].type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
event.target.value = '';
I have checked there are no problem.
now in add.ctp file I adder
<input type="file" multiple />
In output I am seeing the file type field.Now when I clicked on this field and upload a image then mojila bug given me a error.That is
document.querySelector(...) is null error
I have no idea about this error.In here why saying queryselector is null?
document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.
I would suggest you call all JS script bottom of the page.
To make sure that your DOM is ready you could add this to your JS file.
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.querySelector('input[type=file]')
.addEventListener('change', function(event){
...
}
});
This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.
Also take a look at this other Google rule.
file.js
const heading1 = document.querySelector(".heading1");
console.log(heading1);
Solution 1
Use defer (best & recommended way):
<!DOCTYPE html>
<html lang="en">
<head>
<script src="./file.js" defer></script>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
</body>
</html>
Solution 2
Place your JavaScript in bottom before closing body tag
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
<script src="./file.js"></script>
</body>
</html>
I suggest writing your <script type="text/javascript" src="your js file"></script> in body, before the closing tag
There is now another "better" way to address this issue.
put your scripts in the head tag and add the defer attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="main.js" defer></script>
</head>
<body>
yoyoyo
</body>
</html>
you can read more about it here and here
TLDR (may be inaccurate and misleading so read the sources above!):
the defer attribute tells the browser to load the file but hold off its execution until the dom is ready, which is close to the behavior you implicitly get when you put the script tag at the bottom of the body tag, the difference being that in the old way you have to wait for the whole body tag to be parsed until you start downloading the script tag.
I ran into this issue where I was trying to do (slimmed down for simplicity):
<script type="text/javascript">
var svg = document.querySelector('svg');
console.log(svg);
</script>
on an element in the <body>:
<svg id="svg" viewBox="0 0 120 120" width="500px" height="500px"></svg>
Once I added jQuery and moved my lines inside of a $(document).ready(), it was fine:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var svg = document.querySelector('svg');
console.log(svg);
});
</script>
Here's a quick fix. I was trying to effect some changes in my HTML page using DOM and was getting this error. The problem was I linked my Javascript file inside the head tag of the HTML page, when I changed that and linked it at the body just before the closing body tag, it worked!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Soft dog</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.4.1/dist/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link rel="stylesheet" href="landing.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Cormorant+SC:wght#300&family=Edu+VIC+WA+NT+Beginner&display=swap"
rel="stylesheet">
</head>
<body>
<div class="container">
<h2 id="newBrand">Welcome to SOFTDOG</h2>
<p><em>property of soft 6</em></p>
<a id="ceo" href="home.html"><img src="softdogmerch1.jpg" alt="check network"></a>
<p id="enterstatement">Please<a href="home.html">
<P><span>ENTER HERE</span></P>
</a><span>to feed your eyes and fill your wardrobe</span>
</p>
<label for="emailinput">email:</label>
<input id="emailinput" type="email" name="useremail" placeholder="user#email.com" required>
<label for="passwordinput">password:</label>
<input id="passwordinput" type="password" name="userpassword" placeholder="" required>
<input id="clickme" type="submit" name="login" value="log in">
<input id="clickme" type="submit" name="signup" value="sign up">
</div>
<script src="landing.js"></script>
</body>
</html>

Javascript - Changing an image with variables

I'm trying to create a slide show but I'm having some difficulty. I've googled the problem and read loads of pages but I still can't get it to work. I'm doing this all in my header, then the header.php will be included on whichever page. I've tried setting the source to a string containing the location, creating an image before and then setting it to that image's source, and just trying odd things trying to get it to work.
The strange thing is when I call the updateSlider() function, the source of my image is null even though I can see it on the screen, and afterwards when I set it, it says there is a source but the image is the same.
But at the moment I'm just trying to change the image when I click a button and then I'm going to try and make the slide show. Here is the header.php code, you can see some of the different things I've tried in it:
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="all">#import "./includes/layout.css";</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var slideImages = new Array("includes/images/mmSlideImage1.png",
"includes/images/mmSlideImage2.png", "includes/images/mmSlideImage3.png");
var slideImage = newImage();
slideImage.src = slideImages[0];
pic = document.createElement("img");
pic.setAttribute("src", "includes/images/mmSlideImage2.png");
pic.setAttribute("alt", "No Image");
var url2 = "includes/images/mmSlideImage2.png";
var img2 = new Image();
img2.src = url2;
function updateSlider() {
console.log(document.getElementById("ht").getAttribute("src"));
document.getElementById("ht").setAttribute("src", img2.src);
console.log(document.getElementById("ht").getAttribute("src"));
}
</script>
</head>
<body>
<img src="includes/images/mmSlideImage1.png" alt="Logo" width="970" height="278" />
<button type="button" onclick="updateSlider()">Update Slider</button>
<div id="nav">
Home
About
Gallery
Programs
</div>
Thank you in advance for any help!
==================================================================================
UPDATED CODE:
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="all">#import "./includes/layout.css";</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"
</script>
<script>
var url2 = "includes/images/mmSlideImage2.png";
function updateSlider() {
console.log(document.getElementById("ht").getAttribute("src"));
$('ht').attr('src', url2);
console.log(document.getElementById("ht").getAttribute("src"));
}
</script>
</head>
<body>
<img src="includes/images/mmSlideImage1.png" alt="Logo" width="970" height="278" />
<button type="button" onclick="updateSlider()">Update Slider</button>
Simple. You're trying to give an anchor a image attribute. Give your img an id and fix it in the Javascript. For example, if you give it an "currentSlideImage" id:
$('#currentSlideImage').attr('src', url2);
BTW, I'd suggest you take a read on Unobstrusive Javascript.
i am not sure why are you using new image when you are just changing src of an image tag.
the easiest way is to use jquery code
$('#imgTagID').attr('src', url2);
or in javascript
document.getElementById("imgTagID").src = url2;
Here you go you were just missing id Tag inside jquery i just tried it with online images
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var url2 = "http://www.thinkstockphotos.com.au/CMS/StaticContent/WhyThinkstockImages/Best_Images.jpg";
function updateSlider() {
//console.log(document.getElementById("ht").getAttribute("src"));
$('#ht').attr('src', url2);
//console.log(document.getElementById("ht").getAttribute("src"));
}
</script>
</head>
<body>
<a href="index.html" class="logo" > <img id="ht" src="http://www.nasa.gov/sites/default/files/images/743348main_Timelapse_Sun_4k.jpg" alt="Logo" width="970" height="278" /></a>
<button type="button" onclick="updateSlider()">Update Slider</button>
</body>
</html>

pass CSS .class as a parameter to javascript function

the goal here is onclick of 1.gif, everything with .panel1 class disappears(style.display.none), and everything with a .panel2 class becomes visable (style.display.inline)
I'm new at this..so I think its just a syntax issue with ' ' or maybe " "
<!DOCTYPE html>
<html>
<head>
<title>main</title>
<meta charset="utf-8">
<style type="text/css">
.panel1 {display:inline;}
.panel2 {display:none;}
</style>
<script type="text/javascript">
function panelTransition(panelOut,panelIn)
{
document.getElementByClass(panelIn).style.display="inline";
document.getElementByClass(panelOut).style.display="none";
}
</script>
</head>
<body>
<img class="panel1" src=1.gif onclick="panelTransition(panel1,panel2)" />
<img class="panel2" src=2.gif />
</body>
</html>
There is no getElementByClass. It's getElementsByClassName, and it returns an array of items, so you'll need to modify your code to loop through them.
function panelTransition(panelOut, panelIn) {
var inPanels = document.getElementsByClassName(panelIn);
for (var i = 0; i < inPanels.length; i++) {
inPanels[i].style.display = 'inline';
}
var outPanels = document.getElementsByClassName(panelOut);
for (var i = 0; i < outPanels.length; i++) {
outPanels[i].style.display = 'none';
}
}
If you were using a JavaScript library, like jQuery, this would be much easier to do. Also, as has been mentioned, you need quotes around your arguments to panelTransition.
<img class="panel1" src=1.gif onclick="panelTransition('panel1', 'panel2')" />
<img class="panel2" src=2.gif />
<img class="panel1" src=1.gif onclick="panelTransition('panel1','panel2')" />
I think you need quotes there
<html>
<head>
<title>main</title>
<meta charset="utf-8">
<style type="text/css">
.panel1 {display:inline;}
.panel2 {display:none;}
</style>
<script type="text/javascript">
function panelTransition(panelOut,panelIn)
{
// panelIn gets turned on
setDisplay(panelIn,"inline");
// panelOut gets turned off
setDisplay(panelOut,"none");
}
function setDisplay(className,displayState)
{
// retrieve a list of all the matching elements
var list = document.getElementsByClassName(className);
// step through the list
for(i=0; i<list.length; i++) {
// for each element, set the display property
list[i].style.display = displayState;
}
}
</script>
</head>
<body>
<img class="panel1" src="1.gif" onclick="panelTransition('panel1','panel2')" />
<img class="panel2" src="2.gif" onclick="panelTransition('panel2','panel1')" />
</body>
</html>
Or you can accomplish the same in jQuery
// fires when the page is up and running
$(document).ready(function(){
// find all the panel1 elements,
// attach an on click handler
$(".panel1").bind("click", function(){
// find all the panel1 elements
// set their css display property to inline
$(".panel1").css("display","inline");
// find all the panel2 elements
// set their css display property to none
$(".panel2").css("display","none");
});
$(".panel2").bind("click", function(){
$(".panel2").css("display","inline");
$(".panel1").css("display","none");
});
});
You can learn all about jQuery here : http://www.jquery.com/
You'll only be able to get your code to run once, as soon as you click a panel1 image all of the panel2 images will disappear, you won't be able to click them back on ever again.

Categories

Resources