Check if image source is equal to an image - javascript

My current code exists as:
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
function pictureChange(){
if(fixedScreenimg.src == "img/homeScreen.png"){
document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg");
}else{
document.getElementByID("fixedScreenimg").src="img/homeScreen.png");
}
}
</script>
As you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.
I've attempted to use getAttribute and the like.
Any pointers?
Thanks.

Few errors:
ID instead of Id in getElementById function.
Two, unnecessary closing brackets inside if condition.
var elem = document.getElementById('fixedScreenimg'),
btn = document.getElementById('btn');
function pictureChange() {
if (elem.src == "img/homeScreen.png") {
document.getElementById("fixedScreenimg").src = "img/fixedScreen.jpg";
} else {
document.getElementById("fixedScreenimg").src = "img/homeScreen.png";
}
console.log(elem.src);
}
btn.addEventListener('click', pictureChange);
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<button id='btn'>Change src</button>

You actually are adding a closing bracket )
Try the following:
function pictureChange(){
var elem = document.getElementById("fixedScreenimg");
if(elem.src === "img/homeScreen.png"){
elem.src="img/fixedScreen.jpg";
}else{
elem.src="img/homeScreen.png";
}
}

first declare what is fixedScreenimg and the brackets at the 2 statements
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
function pictureChange(){
var fixedScreenimg = document.getElementById("fixedScreenimg");
if(fixedScreenimg.src == "img/homeScreen.png"){
fixedScreenimg.src="img/fixedScreen.jpg";
}else{
fixedScreenimg.src="img/homeScreen.png";
}
}
</script>

Try with single line if condition
function pictureChange() {
var elem = document.getElementById("fixedScreenimg");
elem.src = (elem.src == "img/homeScreen.png") ? "img/fixedScreen.jpg" : "img/homeScreen.png";
}
<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">

You added a bracket at the end of your lines
document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg";

Related

How i show image src on click

Write a function that will be called upon pressing the right button of one of the images you have on the site.
The function calls up a confirm () window in which you ask the user if he wants to know the source of the image
If the user clicks OK alert (this.src), which shows the content of the src attribute of that image
If the user clicks on cancel, disable the context menu that appears at
pressing the right button
this is my wrong code
<img src="opera1.png" id="immagine1" alt="immagine1" width="500" height="333" oncontextmenu="destra()">
<img src="ioaparatissima.JPG" id="immagine2" alt="immagine2" width="500" height="333" oncontextmenu="destra()">
javascript
function destra(){
var r = confirm("Vuoi conoscere la src dell'immagine");
if(r == true) {
alert(y.src);
} else {
}
}
Since you are using inline event bindings I would suggest two changes.
oncontextmenu="destra(this)"
Pass in the element that the inline event binding is on.
function destra(y){
var r = confirm("Vuoi conoscere la src dell'immagine");
if(r == true) {
alert(y.src);
} else {
}
}
Accept the element as a method argument.
By rereading your statement it seems to me that this answer corresponds better ... (?)
document.querySelectorAll('img').forEach(el=> el.addEventListener('contextmenu',destra) )
function destra(e)
{
e.preventDefault() // disable real context Menu
if ( confirm("Vuoi conoscere la src dell'immagine") )
{
alert( this.src )
}
}
<img src="https://picsum.photos/150" alt="immagine1" >
<img src="https://picsum.photos/100" alt="immagine2" >
Use the getElementById(), like in this example:
function destra() {
let r = confirm("Vuoi conoscere la src dell'immagine?");
let y = document.getElementById("immagine1");
if (r == true) {
alert(y.src);
}
}
try like this... I hope this one usefull...
<img src="opera1.png" id="img1" alt="immagine1" width="500" height="333">
<button onclick="getimgId(1)">copy link</button>
<br/>
<img src="ioaparatissima.JPG" id="img2" alt="immagine2" width="500" height="333">
<button onclick="getimgId(2)">copy link</button>
<script type="text/javascript">
function getimgId(img_id){
var res = confirm("Vuoi conoscere la src dell'immagine");
if(res == true) {
var img_id = img_id;
var img_url = document.getElementById('img'+img_id).src;
alert(img_url);
} else {
}
}
</script>
now you want to just give unique id to images and there right side buttons of images...
like img1, img2, img3 for images and onclick="getimg(1)", getimg(2), getimg(3)...
you can easily assign unique ids using Javascript. just apply loop and inside the loops add imgs with unique ids...
for assign unique I share example below...below code is just for Your Reference. do changes as per your needs. you can search on google for more examples.
for(var i=0;i<yourRecordArray.length;i++){
newList = document.createElement('li');
newList.className = 'list-border';
newList.id = 'imgdiv'+i;
newList.innerHTML = '<img src="" id="img'+i+'">+
'<button onclick="">';
document.getElementById('add').appendChild(newList);
i solved like this
function destra(y) {
window.addEventListener("contextmenu", function(e){e.preventDefault();}, false);
var r = confirm("do you want to know the src of the image?");
if(r == true) {
alert(y.src);
} else {
}
}
<img src="https://picsum.photos/150" alt="immagine1"id="immagine1" alt="immagine1" width="150" height="150" oncontextmenu="destra(this)">
<img src="https://picsum.photos/150" alt="immagine2" id="immagine2" alt="immagine2" width="150" height="150" oncontextmenu="destra(this)">

How to change source of image on click to one source and back to different source on same click

When the button is clicked the source of the image must be changed to something and when it is clicked again the source should be changed back to the previous one. Kind of like an animation of sort except that i control it with a button
the code which i have tried and failed is:
DOCTYPE html>
<html>
<body>
<img id="myImage" src="a.png" alt="a" border="0">
<button type ="button" onclick="change()">Click Me</button>
</body>
<script>
var x = document.getElementById("myImage")
function change(){
if x.src="a.png"
document.getElementById("myImage").src = "b.png"
else x.src="a.png"
}
</script>
</html>
What should i change in my code or is there a simpler code
Try this:
var x = document.getElementById("myImage")
function change(){
if (x.src == "a.png")
x.src = "b.png"
else
x.src = "a.png"
}
</script>
Can also do instead of if statement:
x.src = (x.src == "a.png" ? "b.png" : "a.png");
I think this is what you are locking at:
It took me so long to find the pictures, sorry ㅋㅋㅋ
var imgA = 'http://i.imgur.com/v5o8MW8.jpg'
var imgB = 'http://i.imgur.com/v1Vb6RR.jpg'
var x = document.getElementById("myImage")
function change() {
x.src = (x.src == imgA ? imgB : imgA);
}
<body>
<button type="button" onclick="change()">Click Me</button></br>
<img id="myImage" src="http://i.imgur.com/v5o8MW8.jpg" alt="a" border="0">
</body>
You forgot about ():
function change(){
if (x.src="a.png")
document.getElementById("myImage").src = "b.png"
else x.src="a.png"
}
MOAR: https://www.w3schools.com/js/js_if_else.asp
If you are trying to toggle the image you can just use a global variable as below:
var x = 1;
function change(){
if (x == 1)
{
document.getElementById("myImage").src = "../Images/arrow.png";
x = 0;
}
else
{
document.getElementById("myImage").src="../Images/Add.png";
x = 1;
}
}
Harikrishnan's way is one way of doing it. Another way would be by use of custom data-* attributes.
So your HTML would become:
<img id="myImage" data-change="b.png" src="a.png" alt="a" border="0">
And your Javascript would be:
function change(){
var new_src = x.getAttribute('data-change'); // get the new source
x.setAttribute("data-change", x.src); // set the custom attribute to current source
x.src = new_src; // set the image source to new source
}
UPDATE
Just realized you had syntax error and a typo in your solution.
if x.src="a.png"
document.getElementById("myImage").src = "b.png"
else x.src="a.png"
should become
if(x.src == "a.png")
x.src = "b.png"
else
x.src="a.png"
You were missing () in your if statement and also using a single = which will assign a value and not compare values.

How to listen for changes to a img title attribute?

I have a img tag. On click, my CMS adds or removes the post from a favorites area. When the post is not in favorites, the img looks like:
<img src="plus_fav.png" onclick="doFavorites('5', 'plus'); return false;" title="Add to favorites">
When I click on it, the img looks like:
<img src="minus_fav.png" onclick="doFavorites('5', 'minus'); return false;" title="Remove from favorites">
I want to listen for changes for title attribute and write that into some <div id="some-id"></div>. If I have an img with a title="Add to favorites" my code will be like the following after document.ready is fired:
<div id="some-id">Add to favorites</div>
<img src="plus_fav.png" onclick="doFavorites('5', 'plus'); return false;" title="Add to favorites">
When I change the favorite status, the code will be:
<div id="some-id">Remove from favorites</div>
<img src="minus_fav.png" onclick="doFavorites('5', 'minus'); return false;" title="Remove from favorites">
I'm looking for something like .change() but that tracks the title attribute.
Lets do it! :)
This code will work if you have just 2 options (2 kinds of title text - Add to favorites and Remove from favorites)
At first we take to var current title of image
var newTitle = $(".someclass img").attr('title'); // .someclass mean your img parent element class
At document ready append title to your #some-id.
titleChange();
function titleChange() {
$("#some-id").html(newTitle);
}
And then we need to catch click on img and change our newTitle in the opposite value of title.
$(".someclass img").click(function() {
newTitleHolder = $(this).attr('title');
if(newTitleHolder == 'Add to favorites') {
newTitle = 'Remove from favorites';
}else {
newTitle = 'Add to favorites';
}
titleChange();
});
Thats all.
And if you have a lot of images on page with same parent class - just put this code into .each() function.
<img id="img" src="plus_fav.png" onclick="doFavorites('5', 'plus',$(this)); return false;" title="Add to favorites">
<img src="minus_fav.png" onclick="doFavorites('5', 'minus',$(this)); return false;" title="Remove from favorites">
function doFavorites(a,b,c)
{
if(b=='plus')
{
$('#some-id').text('Remove from favorites');
c.attr('title','Remove from favorites');
c.attr('src','minus_fav.png');
c.attr('onclick','doFavorites('5', 'minus',$(this))');
}else if(b=='minus')
{
$('#some-id').text('Add to favorites');
c.attr('title','Add to favorites');
c.attr('src','plus_fav.png');
c.attr('onclick','doFavorites('5', 'plus',$(this))');
}
}
If you want to listen to attribute, there is no direct way, but you can create a watcher that will check every for value and notify if value has updated.
Note: If you have a lot of images, on which you want to watch, this might have performance impact.
Code
JSFiddle
var originalTitle = "";
var count = 0;
var watchInterval = null;
function updateTitle() {
originalTitle = $("#img").attr("title");
console.log("Updating Title")
$("img").attr("title", "New Title " + count++);
if (count > 5) {
console.log("Clearing all intervals")
window.clearInterval(watchInterval)
}
watcher(updateOriginalTitle);
}
function updateOriginalTitle() {
originalTitle = $("#img").attr("title");
}
function watcher(callback) {
var watchInterval = setInterval(function() {
var currTitle = $("#img").attr("title");
if (currTitle != originalTitle) {
console.warn("Title has changed");
if (callback && typeof(callback) === "function")
callback();
}
}, 1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="test.jpg" id="img" title="test Image" onclick="updateTitle()">;
I didn't understood very well...
But i think you want to: Everytime that the title changes it writes a "log".
I'd do:
First identify the img.
<img id="img" src="plus_fav.png" onclick="doFavorites('5', 'plus'); return false;" title="Add to favorites">
And then:
$(function(){
$(document).on("change","#img",function(){
var title = $(this).attr('title');
$('#some-id').append(title);
});
});

Hide/show images button JS

I have a webpage where i have 3 images and I have a button to hide those images all at once on click, and then show them(this part is not implemented yet). I have a JS function for hiding them but it is not working and I have no idea why. So this is part of my code:
<div id="left"><img id="leftimage" name="leftimage" src="pic1url.jpg" style=
"visibility:visible"></div>
<div id="centerright">
<div id="center"><img id="centerimage" name="centerimage" src="pic2url.jpg"
style="visibility:visible"></div>
<div id="right"><img id="rightimage" name="rightimage" src="pic2url.jpg"
style="visibility:visible"></div>
</div><script type="text/javascript">
var hideShowButton = document.getELementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{ document.getElementById(allImages[image]).style.visibility = 'hidden';
document.getElementById(allImages[image+"1"]).style.visibility = 'hidden';
document.getElementById(allImages[image+"2"]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
<div id="buttons">
<input id="hideShowButton" type="button" value="Hide Pics">
</div>
Before reading the answer, I highly suggest you learn how to use the browser's console. It will print all the errors that make your JavaScript code to crash. I also suggest you take some time to read JavaScript tutorials :)
There are many things wrong with your code. First, there is a typo "getELementById" (L is uppercase instead of lowercase). Second, you need to place the script tags bellow your button. Third, when creating an object, you should separate it's properties using commas (,) not semicolons (;) . Finally, you made a false use of the for loop. Just to help you out, here is the corrected code but don't expect people to do that for you every time. You need to find mistakes like these on your own in the future :)
<div id="left">
<img src="pic1url.jpg" id="leftimage" style="visibility:visible" />
</div>
<div id="centerright">
<div id="center">
<img src="pic2url.jpg" id="centerimage" style="visibility:visible"/>
</div>
<div id="right">
<img src="pic2url.jpg" id="rightimage" style="visibility:visible"/>
</div>
</div>
<div id="buttons">
<input type="button" value="Hide Pics" id="hideShowButton" />
</div>
<script type="text/javascript">
var hideShowButton = document.getElementById("hideShowButton");
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage", center:"centerimage", right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
</script>
Use can use diplay none or block property of css to hide and show any view respectively
<img id="one" src="pic1url.jpg" style="display:none;" />
Through javascript you can use this
document.getElementById(one).style.display = 'none';
Sorry, but your code is a bit messy. Why are you using a for statement if then you try to hide every image every time?
By the way, you're misusing the for...in statement. AllImages is a asociative array with no numeric indexes. for (var image in AllImages), image will be 'left', then 'center', then 'right' (the names of the properties of the object you're using). So a statement like
AllImages[image+1]
will return 'undefined' and your code will throw an error. Your code should look like this:
hideShowButton.onclick = function()
{
var allImages = { left:"leftimage"; center:"centerimage"; right:"rightimage"};
if(document.getElementById("leftimage").style.visibility == 'visible')
{
for ( var image in allImages)
{
document.getElementById(allImages[image]).style.visibility = 'hidden';
}
document.getElementById("hideShowButton").innerHTML = "Mostrar imagens";
}
}
By the way, I suggest you to read some documentation about loops in javascript, like MDN

Name an id dynamically with javascript?

How can I dynamically name id's using javascript?
Something like this:
js:
var idName = "fruit";
html:
<img id="javascript:idName" src="banana.jpg">
var bananaImage = new Image();
bananaImage.id = "fruit";
bananaImage.src = "banana.jpg";
Using the jQuery framework you could do something like:
<img class="idName" src="banana.jpg"/>
<img class="idName" src="cherry.jpg"/>
The script ...
var idName = 'fruit';
$(function() {
$('img.idName').each(function(i) {
$(this).attr({id: idName+i});
});
});
... which results in:
<img id="fruit0" class="idName" src="banana.jpg"/>
<img id="fruit1" class="idName" src="cherry.jpg"/>
You can dynamically create elements, such as <img>, and set their attributes using JavaScript's DOM API.
or you can get the element any other way IE
imgs = container.getElementsByTagName("img");
foreach(imgs as img){
if(imgs.src == "banana.jpg") img.id = "fruit";
}
Note: foreach doesn't work in JS you'll need a for loop, but I'm too lazy :P
I think this is what your looking for. You need some sort of event to trigger the JavaScript. Since IMG doesnt have it, except for user events, you need something like:
<head>
<script language="JavaScript" type="text/javascript">
function nameMyIds() {
var idToName = "firstImageId";
var theImage = getImageBySrc("banana.jpg");
if (theImage!=null)
theImage.id = idToName;
}
function getImageBySrc(src) {
// using DOM, using jQuery would make this easier
var allImages = document.body.getElementsByTagName("IMG");
for (var i=0; i<allImages.length; i++ ) {
var img = allImages[i];
var i = img.src.indexOf(src);
if (img.src == src || img.src.indexOf(src) > 0) { return img };
}
}
</script>
</head>
<body onload="nameMyIds()">
<img src="banana.jpg">
</body>

Categories