Swapping an img src with a function (JavaScript) - javascript

I'm trying to swap two imgs in my webpage and can't wrap my head around why this code doesn't work. Any help would be appreciated.
This is in the HTML file:
<img onclick="swap(); "src="LaptopThin.jpg" id="LaptopPicture" />
while this is in a seperate javascript file:
function swap()
{
var picture = document.getElementById('LaptopPicture').src;
if (picture === 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
I changed the code to:
function swap()
{
var picture = document.getElementById('LaptopPicture');
if (picture.src === 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}
and the picture is still not changing at all in the html file. The img stays on Laptopthin.jpg

You can't set the src property of picture because you set picture to the src property of an element already.
Change these lines:
var picture = document.getElementById('LaptopPicture').src;
if (picture === 'LaptopThin.jpg') {
to these:
var picture = document.getElementById('LaptopPicture');
if (picture.src === 'LaptopThin.jpg') {

It is because, the src property will give the absolute value of the image source not just the value set by the src attribute
function swap() {
var picture = document.getElementById('LaptopPicture');
if (picture.src.indexOf('LaptopThin.jpg') > -1) {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}
Another option to try is to use getAttribute
function swap() {
var picture = document.getElementById('LaptopPicture');
if (picture.getAttribute('src')== 'LaptopThin.jpg') {
picture.src = 'ServerRack.jpg';
} else {
picture.src = 'LaptopThin.jpg';
}
}

Related

unable to get property 'style' of undefined or null reference for background colour

Hi I'm getting script error for below code. as I tried all the ways but no luck .
kindly help me as I'm very new to this field. atleast tell me where am I going wrong
<body onload="hightlightMoreLink(2210);hightlightMoreLink(2211);">
function hightlightMoreLink(groupID) {
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)       var moreLinkColumnElement = "";
var moreLinkElement = "";
if (groupID == 2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");        
moreLinkElement = document.getElementById("labelingMoreLink");
} else { 
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color = "#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
(getting error on this line)
moreLinkElement.style.color = "#26339f";
}
}
Here it is working...
function hightlightMoreLink(groupID) {
var isHightlightRequired = 1
var moreLinkColumnElement="";
var moreLinkElement="";
if (groupID==2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");
moreLinkElement = document.getElementById("labelingMoreLink");
} else {
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color="#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
moreLinkElement.style.color="#26339f";
}
}
hightlightMoreLink(2210)
First of all, you should create a fiddle so people can better understand the problem.
Checking your code though, I think the problem is in this line:
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)
Check if it is return a boolean.
Aside from that, I think you should work with classes to manipulate the elements' styles. The onload you're putting on the body is not a good practice either. Jquery has a function for that purpose.
$( document ).ready(){
hightlightMoreLink(2210);
}
Another thing I would point out is the fact that you could use jquery to manipulate the elements. As is:
$("#MoreLinkTH").css("background-color", "#26339f");
$("#labelingMoreLink").css("color", "#fff");

How to change src with onclick?

How change the src of a image with user input src ?
Here is my current JS code ↓
function prmpt () {
var source = prompt ("Enter Image Source ↓")
}
var image = document.getElementById("img"); function changeColor()
{ if (image.getAttribute('src') == "https://api.sololearn.com/Uploads/Avatars/3401170.jpg") { image.src = source; }
else { image.src = "https://api.sololearn.com/Uploads/Avatars/3401170.jpg"; } }
Call the below function on an input of the image source, like onblur. Assign an id to your image for which the image needs to be changed
function imageChanger(newimage) {
document.getElementById("img").src=newimage;
}
You can do this if you prefer:
const changeImg = (newImg) => document.getElementById("img").src = newImg

How can I make an input change its src with an onclick?

I'm trying this and my background changes color (what I want) but the src of the input only changes on the second time I click it. how can I make it change the source on the first click? Also how can I change the src back to the original with a second click?
<input id="showHideContainer" type="image" src="on.png " height="3%" width="2%" alt="On" onclick="toggle();">
<script>
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
divTest.style.display = 'block';
} else {
divTest.style.display = "none";
};
$('body').toggleClass('style2');
$('#showHideContainer').click(function(){
$('#showHideContainer').attr('src', 'off.png');
});
}
</script>
You need to determine the current state of the obj then toggle it with the other
$('#showHideContainer').click(function(){
var off = $(this).attr('src').indexOf('off.png')>-1;
$(this).attr('src', (off?'on.png':'off.png'));
});
Quick fix. You are now attaching anoter eventhandler on the first click on the #showHideContainer, that is why it's not firing the first time. This trimmed version of your code should get you the expected result, also see the other answer to look at the state of your element attribute:
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
divTest.style.display = 'block';
} else {
divTest.style.display = "none";
};
$('body').toggleClass('style2');
var off = $(this).attr('src').indexOf('off.png')>-1;
$(this).attr('src', (off?'on.png':'off.png'));
}

Handling missing images without jQuery

I would like to create a clean solution for handling missing image on the client
using <img src="image.gif" onerror="handleErrors()">
so far the handleErrors looks like this:
function handleErrors() {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
But I feel this is not scalable enough and the no image is also not accessible for screen readers.
What could be a more scalable and accessible solution for this problem?
Try using the alt text attribute for your images.
They are more accessible for screen readers.
Also you can create a module which on error hides the images and
replaces them with their alt text
Here is a module I wrote for handling such issues:
function missingImagesHandler() {
var self = this;
// get all images on the page
self.pageImages = document.querySelectorAll("img");
self.ImageErrorHandler = function (event) {
// hide them
event.target.style.display = 'none';
// replace them with alt text
self.replaceAltTextWithImage(event.target);
}
self.replaceAltTextWithImage = function (imageElement) {
var altText = imageElement.getAttribute("alt");
if (altText) {
var missingLabel = document.createElement("P");
var textnode = document.createTextNode(altText);
missingLabel.appendChild(textnode)
imageElement.parentNode.insertBefore(missingLabel, imageElement);
} else {
console.error(imageElement, "is missing alt text");
}
}
self.attachErrorHandler = function () {
self.pageImages.forEach(function (img) {
img.addEventListener("error", self.ImageErrorHandler);
});
}
self.init = function () {
// NodeList doesn't have forEach by default
NodeList.prototype.forEach = Array.prototype.forEach;
self.attachErrorHandler();
}
return {
init: self.init
}
}
var ImgHandler = new missingImagesHandler();
ImgHandler.init();
HTML:
<img id="myImg" src="image.gif">
JavaScript:
document.getElementById("myImg").onerror = handleErrors();
function handleErrors() {
document.getElementById("myImg").src = "http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png";
return true;
}
Give an ID to image and use this for call your function:
document.getElementById("myImg").onerror = handleErrors();
Giving an ID is more suitable way.

JavaScript link to another page

I have the next code:
<p>
<img alt="" src="imagini/slide1.png"
style="height: 64px; width: 64px" id="imgClickAndChange"
onclick="changeImage()" />
</p>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "imagini/slide1.png")
{
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
}
else
{
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
}
}
</script>
That is changing an image (phase 1) after clicking on it into another image(phase 2). I want to link the second image (phase 2) to an index.php page. How do I do that? Is there a way of altering or interfering in the changeImage function.
Use the else block of the if statement you already have to change window.location.
function changeImage() {
if (document.getElementById("imgClickAndChange").src.indexOf("imagini/slide1.png") !== -1) {
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
} else {
window.location = "index.php";
}
}
You could use jQuery to easily attach a click event on the second image only. Or you could have 2 images in the page (one alone and one inside a link) and then hide and show one image or another.
Try something like this:
var myEl = document.getElementById("imgClickAndChange");
var parent = myEl.parentNode();
var link = document.createElement('a');
link.href = 'http://www.google.com';
link.appendChild(myEl);
parent.removeChild(myEl);
myEl.src = "imagini/platform.png";
parent.appendChild(link);
try this
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "imagini/slide1.png")
{
document.getElementById("imgClickAndChange").src = "imagini/platform.png";
}
else
{
document.location.href="index.php";
}
}

Categories

Resources