Onclick Image button - Logic not making sense [duplicate] - javascript

This question already has answers here:
Difference between object.src and object.getAttribute('src')
(3 answers)
Closed 2 years ago.
I'm having a very confusing time with this very simple onClick function in Javascript/html. I know there are many questions on this but couldn't quite find an answer given what my script does (Or doesn't in this case). It should be simple but for some reason the logic is just not working as I expect it too.
<h1>The onclick Event</h1>
<img id="onoff" onclick="changeImage();" src="images/Off Button.jpg" width="245" height="238">
<p>Click on button to turn "on"</p>
<script>
function changeImage() {
var image = document.getElementById("onoff");
if (image.src.match("Off Button.jpg")){
image.src = "images/On Button.jpg";
}
else{
image.src="images/Off Button.jpg";
}
}
</script>
So as you can see this should take the original "off button" image and swap it to "on button" when it is clicked provided it is showing the "Off Button.jpg".
However, it does nothing, using the Chrome developer tools I can see the script doesn't even fire. But when I make these changes:
if (image.src.match("Off Button.jpg")){
image.src = "images/Off Button.jpg";
}
else{
image.src="images/On Button.jpg";
It now fires and changes the Button to "On Button" but does not fire again to change it back. For me, this makes no sense logically but I might just be missing something really obvious. I know this is pretty basic but any help or explanation would be appreciated.

I did some changes to the code and now it's working.
I used the relative path with ./ to img src and mostly you should avoid use spaces to name images or anything else - spaces always cause problems ;)
<h1>The onclick Event</h1>
<!-- relative path and no space in name on src -->
<img
id="onoff"
onclick="changeImage();"
src="./images/off-button.jpg"
width="245"
height="238"
/>
<p>Click on button to turn "on"</p>
<script>
function changeImage() {
var image = document.getElementById('onoff');
if (image.src.match('off-button.jpg')) { /* no space in name */
image.src = './images/on-button.jpg'; /* relative path and no space
in name */
} else {
image.src = './images/off-button.jpg'; /* relative path and no space
in name */
}
}
</script>
Note - Remember to rename the images inside the images folder as well

Related

Javascript IF-Else not working as expected

HI guys trying to learn javascript and been on w3schools...came across a try me that flipped the image right away from smiley.gif to landscape.jpg...so I decided I was going to see if I learned anything by flipping it with a button instead worked great...but then I decided that on each click I was going to make it go back and forth from smiley.gif to landscape and back to smiley etc...
well thats when the frustration set in..I tried a million ways other then what I originally started with down in the code section...can someone explain to me why this doesnt work..I get no console errors...It still does the initial flip from smiley to landscape on first click but then never changes back to smiley on the second click. Thanks in Advance
<img id="image" src="smiley.gif" width="160" height="120"><br>
<button onclick= myFunc() >Click</button>;
<script>
function myFunc() {
if (document.getElementById("image").src == "smiley.gif") {
return document.getElementById("image").src = "landscape.jpg"
} else {
return document.getElementById("image").src = "smiley.gif"
}
};
</script>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
The Issue
An element's src property returns the full path to the image, including protocol.
Although you've set the attribute to smiley.gif, if you were to console.log the property value, it's something like http://mywebsite.com/smiley.gif. Obviously, this is not equal to smiley.gif.
Using the src property:
console.log(document.getElementById("image").src);
<img id="image" src="test.jpg">
In the future make sure to take these basic debugging steps. If your condition isn't working right, the first step is to verify that the values you're comparing are what you expect them to be.
The Solution
Instead of using the src property, you want to retrieve the src attribute from the element instead. We can do this quite easily using Element.getAttribute().
Using the src attribute:
console.log(document.getElementById("image").getAttribute("src"));
<img id="image" src="test.jpg">
Your if condition should look like this:
if (document.getElementById("image").getAttribute("src") == "smiley.gif")
You should get the src of the img when the page loads so you can compare it as the src gives you the full qualified path of the img source.
<img id="image" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTY2gmwvcnkECDTu_N4qcfJs_5Nh1Usa8v3f-GaAzQcZxL70GpKCA" width="160" height="120"><br>
<button onclick= "myFunc()" >Click</button><br/>
<span id="result"></span>
<script>
var imgsrc = document.getElementById("image").src;
var result = document.getElementById("result");
function myFunc() {
if (document.getElementById("image").src == imgsrc) {
result.innerHTML = "Image source: "+"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVQT4TyiJEFCRA3pmetp3fgZHpgQtzM1hKJMhvAJhOGchqHXQX";
return document.getElementById("image").src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSVQT4TyiJEFCRA3pmetp3fgZHpgQtzM1hKJMhvAJhOGchqHXQX"
} else {
result.innerHTML = "Image source: "+"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTY2gmwvcnkECDTu_N4qcfJs_5Nh1Usa8v3f-GaAzQcZxL70GpKCA";
return document.getElementById("image").src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTY2gmwvcnkECDTu_N4qcfJs_5Nh1Usa8v3f-GaAzQcZxL70GpKCA"
}
};
</script>
compare with == or ===
= sets the value, which is mostly true except you set a falsey value

Why is my div not updating when changing its class with JavaScript?

I currently have a div that's used to display and image via CSS.
For example:
HTML
<div id="myDiv" class="play"></div>
CSS
.play{background: url('../img/playIcon_black.png') no-repeat;}
This image appears as it should.
What I'm attempted to do is to change the image by changing the class (via JavaScript).
Example:
CSS
.pause{background: url('../img/pauseIcon_black.png') no-repeat;}
JavaScript
function myFunction() {
myDiv.className = "pause";
}
When I call myFunction() everything seems to work correctly with one exception. Occasionally the image does not update in the browser.
A few things to note:
I'm certain the function is being called correctly. If I put a console.log() statement within the function, it prints when it should. Additionally, if I inspect the element within the browser, the class is in fact changed to .pause
The image changes from the "play icon" to blank once the function is called, BUT upon hovering over the div the images then appears permanently.
This only seems to happen once the page is initially loaded. Meaning, I can only recreate the issue once upon refresh, then everything works correctly after that.
I have attempted to clear my cache but nothing seems to have changed.
(I'm not sure how relevant this is) I'm calling myFunction() via onended attribute of an audio tag.
For example:
<audio onended="myFunction()"></audio>
But I'm not certain if this would affect anything because the function appears to be called correctly.
Any ideas of why this might be happening?
So the issue is that when you change the class, the browser has to fetch the new image, which takes time. One way to fix the issue is by using sprites, where both images are actually in one image and you only show a piece of that image at a time.
Another solution is to preload the image and then apply the preloaded image source to your new element like this:
var image = newImage();
image.src = '../img/pauseIcon_black.png';
function myFunction() {
var cssBackground = 'url(' + image.src + ') no-repeat';
myDiv.style.background = cssBackground;
// Optionally with jQuery instead:
// $('#myElementID').css('background', cssBackground);
}
Note that if you call myFunction before the image loads you'll encounter the same error. The difference is that this will load the image when the page is loaded (or more properly, when this JS executes and myFunction is assigned) rather than when myFunction is called. To ensure the image is loaded you can use the onLoad event handler for the image object. For more details on preloading images check out this answer: preload image then change background javascript
You need to get the element id
function myfunction(){
var myDivElem = document.getElementById('myDiv');
myDivElem.className = 'pause';
}
You can use document.getElementById("myDiv").className="";in your function
OK if you don't want use first solution you can use second one:
You can add a class to element using
document.getElementById("myDiv").className +=" n";
Then add a class named .play.n to your css file after class named.play
Then add your image address.
If you want to manipulate the div with id "myDiv". Use it as
document.getElementById('myDiv').class
Sample codesnippet: example snippet

Using JavaScript to dynamically change display style in img tags

I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}

Panel only showing on specific page

I need a working javascript code which shows a certain panel only on one specific page on my website and hides it on the rest. It's a forum-esque setup.
Here's what I got so far.
<script type="text/javascript">
function ShowPanel()
{
if(document.location.href == "http://www.exampleurl.com")
{document.getElementById("panel").style.display = "block";}
else
{document.getElementById("panel").style.display = "none";}
}
</script>
<div id="panel" onload="ShowPanel">
Example text.
</div>
According to the example code I've looked up, all of this seems to be reasonable, but obviously there's an error somewhere. Nothing happens.
Thanks for checking!
The problem is that the onload event cannot be used on a DIV element. onload can only be used on the document body or an external resource (iframe, image, scripts).
Your best bet is to place your JavaScript at the bottom of the page instead.
e.g.
<div id="panel">
Example text.
</div>
<script language="JavaScript">
if(document.location.href == "http://www.exampleurl.com"){
document.getElementById("panel").style.display = "block";
}
else {
document.getElementById("panel").style.display = "none";
}
</script>
Check what the document.location.href really is on the page by typing it into your console (F12, usually). For instance, most browsers will add the trailing slash onto a server name even if there isn't one in the URL. The match has to be exact for your code to work as written.
Another options is to compare document.location.pathname, which will have everything after the server name. If you want to make a case insensitive compare, you can use document.location.pathname.toLowerCase().

Way to detect broken images in javascript? [duplicate]

This question already has answers here:
jQuery/JavaScript to replace broken images
(32 answers)
Closed 6 years ago.
I need to be able to detect if an image is broken and replace with a default image if the image link is broken. I know i could do this with an image proxy, but was hoping to do it on the fly with javascript.
I believe it's the onerror event of the img element. onerror=function(){} though i've never used it.
As any event the onerror will propagate upwards on the DOM, so you could make a generic handler for this type of errors.
<script type="text/javascript">
jQuery(document).bind('error', function(event) {
console.log(event.target.src);
});
</script>
You can use <img onerror='doWhateverFunction()' etc etc
http://msdn.microsoft.com/en-us/library/cc197053(v=VS.85).aspx
Example of code:
<script language='javascript'>
function defaultImage(img)
{
img.onerror = "";
img.src = 'default.gif';
}
</script>
<img alt="My Image" src="someimage.gif" onerror="defaultImage(this);" />

Categories

Resources