JavaScript element src change - javascript

So I have two images, "safety-pin-green" and "safety-pin-blue" and I want to change the image elements source depending on which the contents of the source when called, this will be for mouse over and mouse out.
Here's the JavaScript:
function changeImage(id) {
var src = document.getElementById(id).src;
if (src.search("green") != 0) {
src = src.replace("green", "blue");
} else {
src = src.replace("blue", "green");
}
document.getElementById(id).src = src;
}
and the HTML tag i'm using:
<img id="safety-pin" src="../images/safety-pin-green.jpg" alt="Safety pin"
onmouseover="changeImage(id)" onmouseout="changeImage(id)"></img>
The code almost works, the images go blue, but they don't return to the green image when the mouse leaves the image, any ideas why this is?

From MDN documentation of search,
Return value
The index of the first match between the regular expression and the given string; if not found, -1.
Replace
src.search("green") != 0
with
src.search("green") !== -1

I fixed it :) a simple '>' solves my problem.
if (src.search("green") > 0) {
src = src.replace("green", "blue");
}...

Related

Loop through all images inside links, extract image name from the image path and convert it into a string with jQuery

$("a > img").each(function () {
if ($(this).attr("alt") == undefined || $(this).attr("alt") == "") {
var name = $(this).attr('src');
name.replace(/(\/+\.+\-+)w+?/, "");
$(this).attr('alt', name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to get all images inside a link that don't have an ALT tag. Then get the image name as a string and add it as ALT tag to the image. Everything works fine except for the regular expression. Right now it's adding the image path as an ALT which doesn't fix my ADA issues.
The reason i am doing that is because i am trying to fix the ADA issues on the website. (Every image inside a link must have an alt tag)
You need to reassign the updated value after replace to name variable again and then update the image alt attribute like:
name = name.replace(/(\/+\.+\-+)w+?/, "");
$(this).attr('alt', name);
// If a link has an image and no aria label
//Get image source, strip everything except for image name
//Add image name as aria-label to the link
$('a:has(> img)').each(function () {
var URL = $(this).children('img').prop('src');
var output = URL.split('/').pop();
output = output.replace(/[- .\s]/g, " ");
$(this).attr('aria-label', output);
});

Replace certain img src with another via javascript

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");
};
};

Inner HTML if statement not recognizing a div tag

I tested the following code in IE, Chrome, and Firefox and it does not work in any of them. I have read several questions about similar problems but they have not offered solutions that fix my example.
I am trying to create a pause/play button that interfaces with JWplayer (I also want it to interface with flowplayer, once I get the button working) and the image will change depending on which image is currently there. I also have a stop button that stops the player completely and changes the image of the pause/play button to pause.
Here is my current code:
<script type="text/javascript">
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML == imgtag2)
{obj.innerHTML = imgtag1;}
else
{obj.innerHTML = imgtag2;}
return;
}
function playimg()
{
document.getElementById('image1').innerHTML = '<img src=\'PLAY.png\'>';
return;
}
</script>
<div id="image1" href="#" onclick="changeimg(); jwplayer('mediaspace1').play(); jwplayer('mediaspace2').play(); jwplayer('mediaspace3').play(); jwplayer('mediaspace4').play();"><img src='PLAY.png'></div>
<div href="#" onclick="playimg(); jwplayer('mediaspace1').stop(); jwplayer('mediaspace2').stop(); jwplayer('mediaspace3').stop(); jwplayer('mediaspace4').stop();"><img src='STOP.png'></div>
The play/pause function works, and the first div WILL change into the pause img (so the javascript is going through) and it WILL change back into play if I click on the second div (stop function - triggers playimg() ) but it will not change back into the play image if I click on the pause button again.
For security reasons I can't link the website, but any help would be appreciated
It looks like all you really want to change is the SRC of the IMG tag, not necessarily the entire innerHTML. As machineghost mentions in his comment, there may be whitespace added or other changes to the full HTML that may make your comparison come out as false.
However, you could check if obj.src == "PLAY.png" and set the SRC attribute directly. Something like this:
function changeimg()
{
var obj = document.getElementById('image1');
var img1 = 'PLAY.png';
var img2 = 'PAUSE.png';
if(obj.src == img2)
{obj.src = img1;}
else
{obj.src = img2;}
return;
}
I think the innerhtml you are replacing in changeimg() is affecting the whole obj element, which is a div. So, if(obj.innerHTML == imgtag2) will return false since the div innerhtml is not imgtag2, but the next time you are going to call changeimg(), "obj" will be undefined because you replaced its innerhtml with an HTML code that doesn't have an id: {obj.innerHTML = imgtag2;}
Check the console to see if there's any javascript error, which it should, at if(obj.innerHTML == imgtag2)
rgds.
Just check whether PLAY is present or not and then change innerHTML according to it
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML.indexOf('PLAY') != -1)
{obj.innerHTML = imgtag2;}
else
{obj.innerHTML = imgtag1;}
return;
}

How to replace all empty <img src=""> on a page with JavaScript on dom loaded?

I need a function, that starts, when the DOM is loaded.
In my HTML Page are several empty Image Tags, like and I want to add an Image-Name into the src-property when everything is loaded to get something like
<img src="blank.jpg">.
Best wishes
Chris
Construction <img src=""> is invalid. Never use it.
It's invalid because empty url means url to current page. But current page is HTML document, not image. Browser can make another query of current page and try to use it as image (see this page).
function replaceSrc()
{
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++)
{
var img = images[i];
if(img.src.length == 0)
{
img.src = 'blank.jpg';
}
}
}
window.onload = replaceSrc;
OR if you want to add more than one handler for the event:
document.addEventListener('load', replaceSrc, false) //W3C
document.attachEvent('onload', replaceSrc); //IE
With jQuery
$(document)
.ready(function() { $('img')
.filter(function(){ return this.src.length == 0 })
.each(function () { this.src = 'blank.jpg'}) });
EDIT:
I realized that you probably want to set the src property before the images load so I changed the code to fire on the document's load event, which happens before the images start loading.
Use jQuery! It's easy.
$('img').attr('src','new-image-name.jpg')
This will set the src attribute of every img tag to 'new-image-name.jpg'.
With jQuery, this would set the src attribute of all img elements with a blank src attribute to "blank.jpg" on page load.
$.ready(function() {
$("img[src='']").attr("src", "blank.jpg");
});
You can use this script.
# Script AddImage.txt
var string pagefile, image, html
# Read in the page file.
cat $pagefile > $html
# Replace all instances of "<img src="blank.jpg">" with the specified image.
while ( { sen -r -c "^<img src=&\>^" $html } > 0 )
sal -r -c "^<img src=&\>^" ("<img src=\""+$image+"\">") $html > null
# Write page back.
echo $html > { echo $pagefile }
Script is in biterscripting. Save the script in file "C:/Scripts/AddImage.txt", run it with this command.
script "C:/Scripts/AddImage.txt" pagefile("/path/to/page.html") image("blank.jpg")
It will replace previous image with "blank.jpg".
With JQuery you can simply solve your problem using following code.
$(function(){
$("img[src='']").attr("src", "blank.jpg");
});
Replace images if null from API data using dom manipulation
const images = document.getElementsByTagName('img');
for(const img of images){
const src = img.getAttribute('src');
if(src === "null" && strGender === "Male"){
img.src = "img/placeholder-male.jpg";
} else if(src === "null" && strGender === "Female"){
img.src = "img/placeholder-female.jpg"
}
}

how to get the image source in javascript?

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;
}

Categories

Resources