how to get the image source in javascript? - 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;
}

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

Attempting to change an image onclick via PHP/Javascript/HTML

I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
 
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
 
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}

JavaScript element src change

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

how to add text and images together on a function load

I have a function in which when the function is called I need to have text and an image pop up. My javascript is:
function Upload(){
if(value !- ''){
$("#divValue").html("Uploaded: " + //i need to add an image here );
}
So where it says //I need to add an image here, this is where my image, lets say its tire.gif, needs to be added so when the javascript is called it displays the text and image together.
you can use document.createElement method to create a img Object and simply set the source and optional height and width, then add it to your div using "append":
var img = document.createElement('img')
img.src = //URL to your image
$(img).css('width','50px'); //set the width (optional)
$(img).css('height','50px'); //set the height (optional)
//finally append the newly created image object to your "DivValue"
$("#divValue").append(img);
Can you try this,
function Upload(){
var value="some value";
if(value != ''){
$("#divValue").html("Uploaded: <img src='../images/tire.gif' />" );
}
}
It is actually pretty straight forward. You just need to pass the tag inside the string that will replace the html.
Check this jsFiddle
But you just need to do:
$("#divValue").html("Uploaded: <img src=' PATH_TO tire.gif ' /> ");
Watch the difference between " and ' to avoid syntax problems.
Cheers.
You mean like this?
$("#divValue").html('Uploaded: ' + '<img src="image.jpg" alt=""/>');

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

Categories

Resources