I want to make a simple switch of <img src="..."> depending on the present src with JavaScript. So if the image #plus_1 is clicked, the script should check if the string 'plus' is in the src attribute, and if yes, the src attribute should change.
Not sure what mistake I made, help would be very much appreciated!
JavaScript:
function ek_ak(id) {
var ement = document.getElementById(id);
if (ement.img.src.includes("plus") == true) {
ement.img.src == "minusred.png";}
}
HTML
<img src="plusred.png" id="plus_1" onclick="ek_ak('plus_1')"/>
A few pointers:
ement is already a DOM element: it has no img property but you can access src on it directly;
Regular expressions can be used instead of String#includes;
You should use = as the assignment operator, instead of == (loose comparison).
function ek_ak (id) {
var ement = document.getElementById(id);
if (/plus/.test(ement.src)) {
ement.src = "minusred.png"
console.log(ement.src)
}
}
<img src="plusred.png" id="plus_1" onclick="ek_ak('plus_1')" />
You can directly send the element to the function using onclick="ek_ak(this). This will avoid the unnecessary call to retrieve the element.
To get the src you can simply call element.src. The element is your img
The call .includes(..) is returning a boolean value. You do not need to add == true.
You were using element.src == "minusred.png. == is used to compare elements not to assign. You should use =
function ek_ak(element) {
console.log("Current src = " + element.src);
if (element.src.includes("plus")) {
element.src = "minusred.png";
console.log("Next src = " + element.src);
}
}
<img src="plusred.png" id="plus_1" onclick="ek_ak(this)" />
Related
New to JS. I am trying to toggle between showing two images, dragon.svg, and dragon1.svg, every 1 second starting on page load, and running indefinitely. However, my image only changes once, and then keeps running every second but not following the rules of my if/else statement.
My suspicion is that the function is not changing the value of a global variable called dragonDiv each time it runs, so each time it runs, it is using the original value of the dragonDiv variable.
On the HTML, I have a div with the image inside, like this:
<body onload="changeDragon();">
<div id="dragonarea">
<img src="images/dragon.svg"/>
</div>
</body>
And then I have this JS, which should change the image to dragon1.svg if it is currently dragon.svg, and vice versa, every 1 second.
function changeDragon() {
changeInterval = setInterval(dragonColorChange, 1000);
}
let dragonDiv = document.getElementById('dragonarea');
console.log(dragonDiv.innerHTML); // Correctly logs <img src="images/dragon.svg"/>
function dragonColorChange() {
if (dragonDiv.innerHTML = '<img src="images/dragon.svg">') {
dragonDiv.innerHTML = '<img src="images/dragon1.svg">';
console.log(dragonDiv.innerHTML) // Correctly logs <img src="images/dragon1.svg"/>
} else {
dragonDiv.innerHTML = '<img src="images/dragon.svg">';
console.log(dragonDiv.innerHTML) // Never makes it to this point
}
}
As noted above, the console log tells me that it is correctly changing the image the first time, but after that, it seems like it is again taking the original value of dragonDiv (with the dragon.svg image) and running the function on that innerHTML again (so changing it to dragon1.svg again), rather than updating the innerHTML after running the function once as I'm telling it to do and forcing it to the else statement.
I tried putting the dragonDiv variable inside the dragonColorChange function as well as outside as a global variable. I tried using document.getElementById('dragonarea').src instead of replacing the entire innerHTML of the div tag. I tried using === instead of just =. I tried various other things for about 4 hours and I can't figure out how to get it to keep looping through the if/else statements.
Any mistakes I'm making in my code?
Apart from the typo (= is assignment, == or == is comparison) you have several improvements you can make
Use addEventListener
Change src, not innerHTML, waste of DOM rendering
I suggest a data-attribute
let changeInterval;
let dragonImage;
window.addEventListener("load", function() {
dragonImage = document.getElementById("dragonImage");
changeInterval = setInterval(dragonColorChange, 1000);
})
function dragonColorChange() {
const toggle = dragonImage.dataset.toggle
const src = toggle === "0" ? "images/dragon1.svg" : "images/dragon.svg";
dragonImage.src = src;
dragonImage.dataset.toggle = toggle === "0" ? "1" : "0";
}
<div id="dragonarea">
<img id="dragonImage" data-toggle="0" src="images/dragon.svg" />
</div>
Typo I guess, use === or == for comparison.
Also, onload function on body had different quotes [”] (when I copied and pasted on jsfiddle, it didn't work) instead of ["]
function changeDragon() {
changeInterval = setInterval(dragonColorChange, 1000);
}
let dragonDiv = document.getElementById('dragonarea');
/* console.log(dragonDiv.innerHTML); // Correctly logs <img src="images/dragon.svg"/> */
function dragonColorChange() {
if (dragonDiv.innerHTML === '<img src="images/dragon.svg">') {
dragonDiv.innerHTML = '<img src="images/dragon1.svg">';
console.log(dragonDiv.innerHTML) // Correctly logs <img src="images/dragon1.svg"/>
} else {
dragonDiv.innerHTML = '<img src="images/dragon.svg">';
console.log(dragonDiv.innerHTML) // Never makes it to this point
}
}
<body onload="changeDragon();">
<div id="dragonarea">
<img src="images/dragon.svg" />
</div>
</body>
Here I compare and change the image.src directly, instead of the div's innerHTML, as others have suggested already.
HTML:
<body onload="changeDragon();">
<div id="dragonarea">
<img id="dragon-image" src="images/dragon.svg"/>
</div>
</body>
JavaScript:
function changeDragon() {
changeInterval = setInterval(dragonColorChange, 1000);
}
let dragonImage = document.getElementById('dragon-image');
function dragonColorChange() {
if (dragonImage.src === 'images/dragon.svg') {
dragonImage.src = 'images/dragon1.svg';
} else {
dragonImage.src = 'images/dragon.svg';
}
}
As others have said you need the ===.
Here's one way to do it and keep the variable scoped to the function. I'm using .getAttribute("src") instead of just .src since it gets the relative url path.
Note that dragonColorChange isn't being passed into setInterval. It's the function returned by calling dragonColorChange.
const changeDragon = function () {
changeInterval = setInterval(dragonColorChange(), 1000);
};
function dragonColorChange() {
let dragonImg = document.querySelector('#dragonarea img');
return function () {
dragonImg.src = dragonImg.getAttribute("src") === "images/dragon.svg" ? "images/dragon1.svg" : "images/dragon.svg";
}
}
In the if condition there is a typo. Instead of comparison with == or === there is assignment operator which will assign rather than compare. Try changing that to comparison.
I want to set img src=" " with a function in javascript that changes the picture upon a variable and checks values:
javascript file code:
function myFunctionstatus(){
var ledactual=document.getElementById("ledonof").value
var image = document.getElementById('ledPic');
if (ledactual==ledon) {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-c
content/uploads/OFFbulb.jpg";
}
if (ledactual==ledoff){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-
content/uploads/ONbulb.jpg";
}
} };
img src in html file:
<img id="ledPic" [src]="myFunctionstatus()" >
but it didn't work with me and the picture didn't appear! the script is working, I tested with a button:
<input type="button" id="ledonof" onclick="myFunction();myFunctionstatus();" class="ledonoff" value="<?phpinclude ('ledstatus.php'); ?>">
how can I set img src with a function?
I can't comment on the php that you're using to get the status, but the below is a working javascript example:
function myFunctionstatus(){
var input = document.getElementById("ledonof");
var image = document.getElementById('ledPic');
if (input.value == "on") {
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
input.value = "off"
} else if (input.value == "off"){
image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
input.value = "on"
}
}
myFunctionstatus()
<img id="ledPic" />
<input type="button" id="ledonof" onclick="myFunctionstatus();" class="ledonoff" value="on">
As noted by others, src doesn't support function calls (and you don't even return anything from your function call), so you need to run the function once at the start to set the image to the initial status.
You need to set an initial state manually
function switchStatus() {
let switchButton = document.getElementById('ledonof');
let img = document.getElementById('ledPic');
if(switchButton.value == "ledon") {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
switchButton.value = "ledoff";
} else {
img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
switchButton.value = "ledon";
}
}
<img id="ledPic" src="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg" > <input type="button" id="ledonof" onclick="switchStatus();" value="ledoff">
img src attr does not support function call. Whatever you pass in the src will be considered as url(relative or otherwise).
Please refer https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes
So what you need to do is call the function before/loading your element and change the src then. The simplest form would be following
`<script>
(function() {
// your page initialization code here
// the DOM will be available here
// call the function here
})();
</script>`
You can't do this. The src attribute of an image element can't be interpreted as javascript when the HTML is interpreted.
initially, you need to set src, and on button click, you can toggle image by changing image src.
I'm trying to replace all the src for all images on my page when the src is something specific:
$("img").each(function(i, elem){
if ($(this).attr("src") == "/images/oldimage.png"){
console.log("yay!") //this doesn't log anything
$(this).attr("src", "/images/mynewimage.png");
}
});
I figured the above would work, but it doesn't seem to be. It's not finding anything that matches my if statement, which I tested with the console.log, but there are lots of img that should match.
You can use getAttribute and setAttribute to make this.
var aExample = document.querySelectorAll("img");
for(var i = 0; i < aExample.length; i += 1) {
if(aExample[i].getAttribute("src") === "images/old.png") {
aExample[i].setAttribute("src", "images/new.png");
};
};
So I am having issues with captioning my slide show using a javascript, can somebody let me know as to where I am going wrong. My code stands as this:
JavaScript Document
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
if( img.attr("src") == "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
HTML document
<div class="slides">
<img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>
Also to note, that I get this error within the "inspect element":
Uncaught TypeError: Cannot call method 'attr' of null
REVISED
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();
}
function CaptionSlide()
{
window.onload = function(){
if( img.src === "movieImages/img1.jpg")
document.getElementById("captionbar").innerHTML="Up!";
else if(img.src === "movieImages/img2.jpg")
document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.src === "movieImages/img3.jpg")
document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.src === "movieImages/img4.jpg")
document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.src === "movieImages/img5.jpg")
document.getElementById("captionbar").innerHTML="Ice Age";
}
}
The HTML Remains the same as before.
No error references however function does not write the text whatsoever.
Replace all img.attr('src') by img.src=="your image name".
For example:
img.src=="movieImages/img1.jpg"
As you are using pure JavaScript,you cannot use attr() which is method of JQuery.
attr() is a method brought by JQuery. If you are not using JQuery, you should keep using img.src. Another thing I noticed that might cause trouble : when you read .src from your image, you get the full path as a return (including your domain).
Your conditions would then become :
img.src === "http://yourdomain.com/movieImages/img1.jpg"
( And I just checked to be sure : http://www.w3schools.com/jsref/prop_img_src.asp mentions that the return value of img.src includes protocol and domain )
Also I think you should either define your function CaptionSlide inside moveToNextSlide so that it gains access to the updated img variable or not declare your img variable inside the moveToNextSlide function (so that the global variable gets updated instead)
Another point : you should make sure the DOM is loaded before querying elements from it (such as img) . To do so, wrap your code in a function, and assign it to the window.onload event :
window.onload = function() {
var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");
function moveToNextSlide()
{
...
}
function CaptionSlide()
{
if( ... )
...
}
document.getElementById("button").addEventListener('click', moveToNextSlide);
}
and HTML for button :
<input type="image" src="images/Next.png" id="button" title="Next" />
I want to compare if the chosen image equal to the desired image..
Here's the initial code but is not working
function mouseOut(txt){
var imgClick, imgOrig; imgClick = 'images/'+txt+'_onclick.png'; imgOrig ='images/'+txt+'.png';
if(document.getElementById(txt).src == imgClick){return false;}
else {document.getElementById(txt).src = imgOrig};
}
Then on img
<a href = "#"><img src="images/leistungen.png" alt="leistungen" name="leistungen" width="162" height="38" id="leistungen"
onclick="MM_swapImage('home','','images/home_orig.png','philosophie','','images/philosophie.png','kontakt','','images/kontakt.png','body_layout','','images/body_leistungen.png',0)"
onmouseover="MM_swapImage('leistungen','','images/leistungen_onclick.png',1)"
onmouseout="mouseOut('leistungen')" /></a>
My question again is
if(document.getElementById(txt).src == imgClick)
This is wrong but I want to compare if the current image (mouseover,onclick,onmouseout) is equal to an image filename
let say I have these images... home.png and home_onclick.png
the default image is home.png, if onmouseover the image will change to home_onclick, and if on mouseout it will change to home.png if and only if onclick event is not triggered.
Thanks in advance
SRC will return full path of the image. Hence if you need to compare,
put your values of imgClick as full URLs, and not relative.
ie imgClick = "http://www.mysite.com/images" +txt+'_onclick.png';
( you can also use window.location.protocol + "//" + window.location.host instead of your sitename )
Another approach is to check if the src contains imgClick
if(document.getElementById(txt).src.indexOf(imgClick) > 0){
return false;
}
else {
document.getElementById(txt).src = imgOrig;
}