Changing IMG SRC with Javascript - javascript

I'm new at javascript and while there are many more complex solutions, I don't understand them and hope I don't have to at this point.
I have a main picture...
<img src="main-picture.jpg" name="Mainpic" id="image">
...and I want to be able to change this picture when I click on one of two thumbnails.
<img src="replacement1.jpg" name="pic1">
<img src="replacement2.jpg" name="pic2">
My javascript code I thought would be super easy. I'm currently using...
function FirstPic(){
document.Mainpic.src = document.pic1.src
return
}
function SecPic(){
document.Mainpic.src = document.pic2.src
return
}
Now the variable is changing however it's not staying changed. When the thumbnail is clicked on, the replacement picture flashes on the screen and then it returns to the original main-picture.jpg.
How do I make the change permanent until a different thumbnail is clicked?
Thanks!

I think it's flipping back because your page is reloading.
You need to return false from your onclick= if you don't want the href= value to activate after your onclick.
Also, you can set href="#" just in case. # goes nowhere (doesn't ever reload the page)

I think your page is refreshing by your click, change your links as :
<img src="replacement1.jpg" name="pic1">
<img src="replacement2.jpg" name="pic2">

Why not do something like this (haven't checked the syntax completly, so it could be faulty.
function FirstPic()
{
var pic1 = document.getElementById("pic1");
if (pic1 == typeof('undefined')) return;
pic1.src = "newpicname.jpg";
}
Make sure you give the tags an ID attribute called pic1 and pic2 (instead of a name attribute) and give the image itself an 'onclick' attribute...
<img onclick='FirstPic()' id='pic1' src='image1.jpg' />

Related

Automatically generate <a> tag from <img> tag

I have a page where the following pattern happens quite often:
<a href="path/to/image.jpg">
<img src="path/to/image.jpg">
</a>
In order to avoid typos, I'd prefer to only have to enter the image and path once.
Is there a way (preferably using only native HTML/JS/CSS) to avoid that duplication?
Only recent browsers need to be supported.
Edited to add: there's one location in the page that has a similar but possibly conflicting pattern:
<a href="https://a.web.site/">
<img src="image.jpg">
</a>
I could get rid of it if needed.
But maybe a more robust solution would be to start from something like:
<a href="path/to/image.jpg">
IMG_LINK_TO_CREATE
</a>
and to replace a predefined pattern with the img tag, rather than the other way around.
To fit my answer to your question, I'll only use Vanilla JavaScript. Also, since it's not clear for me if you are trying to create an img from an anchor or viceversa, I am doing both for you. I'll put first the one that appears in you question title.
Identify your elements:
If you want this to work, you need to give at least a class or unique id attribute to your anchor tag in order to properly modify it later on when they are loaded into the DOM.
Generate anchor tag for an image tag
For this case, since you probably will be using multiple anchors and you'll have to do the same for every anchor you want, a class attribute with "create-link" would be enough for you to easily modify these elements directly from the DOM. Something like this would help:
<img class="create-link" src="path/to/image.jpg">
With this said, you can create a function called generateImages() which will do all the work.
function generateImages(){
let images = document.querySelectorAll(".create-link");
images.forEach(image=>{
let link = document.createElement('a'),
parent = image.parentNode,
childImage = new Image();
link.href = image.src;
link.classList.add('generated-link');
childImage.src = image.src;
link.append(childImage);
image.parentNode.removeChild(image);
parent.append(link);
});
}
And that should do it. You can now just execute it whenever you want or in the window load event.
window.onload = generateImages;
Here is a fiddle to help you visualize the overall of this method.
https://jsfiddle.net/m90b6vc5/1/
Generate image from anchor tag:
Same thing as the other one, identify your elements that you will need to use in JavaScript in the future.
The code would be a little bit easier to this, just need to retrieve the link from the anchor tag and append it to a new image element:
function generateImages(){
let a = document.querySelectorAll(".create-link");
a.forEach(element=>{
let image = new Image();
image.src = element.href;
element.append(image);
});
}
https://jsfiddle.net/m90b6vc5
You can do this. But note that this only adds the img after the page is loaded. which means the users view can be re-rendered after the page loads. You can control it to some extent by defining the expected img with-height or ratio in the .img-link class using css
$(document).ready(function(){
$('.img-link').each(function(){
$(this).append($('<img src="' + $(this).attr('href') + '" />'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<a href="custom-link">
<img src="custom-image.jpg" />
</a>
javascript function
function createImageStructure(number, imageArray){ var structure = "";
for(var i = 0; i < number; i++){
structure += ' <img src="'+imageArray[i]+'"> ';
} console.log(structure); }
var imageArray = [];
imageArray.push("https://pay.google.com/about/static/images/social/knowledge_graph_logo.png");
imageArray.push("https://pay.google.com/about/static/images/social/knowledge_graph_logo.png");
createImageStructure(2, imageArray);
output
<img src="https://pay.google.com/about/static/images/social/knowledge_graph_logo.png"> <img src="https://s23527.pcdn.co/wp-content/uploads/2018/05/google-photos.png">
basically, create a function, create an array, to have image paths, this will help to create HTML structure with multiple images.
if need more help please let me know, i will fix this, if you want just one image source path for all img tags
While I really don't want to encourage you to do this with client-side code, I will at least suggest you use code that generates links instead of code that generates images. This way, the website still shows images if the JS doesn't run.
The simplest way to do this is to add a class to all images which you want to automatically wrap in a link, such as "auto-link", and then run this code:
for (const img of document.querySelectorAll(".auto-link")) {
const link = document.createElement("a");
link.href = img.src;
img.parentElement.replaceChild(link, img);
link.appendChild(img);
}
You can put this in an "domready" or "load" event listener, or just in a script tag at the end of the page.
Note that pretty much all browsers have a "view image" option in their context menu, so there's no reason to do this. You shouldn't introduce a dependency on JavaScript, which slows down execution and wont work if you disable JS or use a screen reader. Instead, features like these ought to be done server-side or as a compilation step.
A good way to encapsulate your html and reuse it elsewhere is React.
function AImg({ href, src }) {
return <a href={ href || src }>
<img src={ src }/>
</a>;
}
ReactDOM.render(
<div>
<AImg src="https://placecage.com/./200/200" />
<AImg src="https://placecage.com/c/200/200" href="https://placecage.com"/>
<AImg src="https://placecage.com/g/200/200" />
</div>,
document.getElementById('aimg_container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="aimg_container"></div>
React.js is good way to go. If you want to still use ES6 only you can use also backticks. Add links to images and links in an array and in a for of loop create links with image. Something like:
const urls = ['1', '2', '3'];
const images = ['a','b','c'];
let links = [];
for (let index of urls.keys()) {
links.push(`
<img src="${images[index]}" />
`);
}
Adding elements to the DOM can be expensive. I would not be adding a tags via javascript. Keep your HTML mostly as is, but leave the href attribute empty for the links you want to populate.
I've also given you the option of populating the image source based on the href. This is not as good as the image has to be loaded after the page is rendered.
//Wait for everything to be loaded
document.addEventListener("DOMContentLoaded", function(){
//Find a tags with empty hrefs
let emptyAs = document.querySelectorAll("a[href='']");
emptyAs.forEach((a) => {
//Update href based on image src
a.href = a.querySelector("img").src;
});
//Alternatively Find images with empty src
let emptyImgs = document.querySelectorAll("img[src='']");
emptyImgs.forEach((img) => {
img.src = img.parentNode.href;
});
});
<a href="">
<img src="https://fillmurray.com/200/200" />
</a>
<a href="">
<img src="https://fillmurray.com/100/100" />
</a>
<a href="https://fillmurray.com/300/300">
<img src="" />
</a>
<a href="http://www.google.com">
<img src="https://fillmurray.com/400/400" />
</a>
Note forEach has no IE support for a node list: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

How to execute javascript function when the user clicks on the image

I want to call or execute javascript function when user click on image. I have javascript file with many functions and one of them is ShowKeybord(). So i want to execute this function ShowKeybord() when user clicks on image.
I tried with HTML parameter onclick: <img src = "' + content + '" alt = "Heads" onclick = "ShowKeyboard()" height="170" width="170"/> but its not working.
Here is my code of key functions that are related to my problem.
I tried with header.addEventListener('click', ShowKeyboard) and work properly but the keyboard is displayed when you click anywhere in the header of the web page. I would however like to make the keyboard appear only when a user clicks on the image.
What am I doing wrong and what should change depending on my code?
Thank you very much for your help.
You can also try to encapsulate your img with a div with the attribute onclick="ShowKeyboard()"
Wich gives something like this
<div onclick = "ShowKeyboard()">
<img src = "' + content + '" alt ="Heads" height="170" width="170"/>
</div>
It's better to enclose your image inside a div tag. As suggested by #Lucas Duval.
This should definitely work if not please give your div an "ID" or "class" and try to handle this with JQuery.
Thanks!
in the head tag put
<script src="yourjavascriptfilepath"></script>
and should work.
or maybe try onclick="ShowKeyboard()" rather than onclick = "ShowKeyboard()"
I think that has to do something with it.

Modify onclick with a separate onclick event

I have three clickable images. One image on the first row, two images on the second row. The image on the first row is a reflection of whichever image on the second row was last clicked. I can make the image on the second row modify the src of the image on the first row, but am having difficulty modifying the onclick parameter of the anchor tag. I can't just change the href of the first image, it has to actually mimic the clicking of the second row image. Here's my code, along with by a jsfiddle of it:
https://jsfiddle.net/2hgzmnmb/
<a onclick="document.getElementById('image1').click();" id="previewLink"><img id="previewImage" src="http://i.imgur.com/UevhwuA.png"></a>
<br><br>
<a id="image1" onclick="document.getElementById('previewImage').src='http://i.imgur.com/UevhwuA.png';alert('1')"><img src="http://i.imgur.com/UevhwuA.png"></a>
<a id="image2" onclick="document.getElementById('previewImage').src='http://i.imgur.com/121fy0E.png';alert('2')"><img src="http://i.imgur.com/121fy0E.png"></a>
I want to add the following: document.getElementById('previewLink').onclick='document.getElementById('image1').click();' to the onclick parameter for the first image on the bottom row, and: document.getElementById('previewLink').onclick='document.getElementById('image2').click();'
to the second image on the bottom row, so the image on the first row will not only look like whichever image was last clicked on the second row, but will also mimic the actual click. Right now, obviously from the code, it will only mimic clicking the first image on the second row, no matter what image was last clicked, and I'm thinking it's because my syntax isnt correct when I try to modify the onclick property of the anchor tag for the image on the first row.
I also tried doing this with variables but got a bit tied in knots.
Any ideas on how I could go about doing this? I'm close, just not there yet.
Thanks!
Fiddle: https://jsfiddle.net/2hgzmnmb/1/
this: document.getElementById('previewLink').onclick='document.getElementById('image1').click();'
should be:
document.getElementById('previewLink').onclick=this.onclick
because onclick attribute is actually running a JS code, so if you pass a string there, it will interpret it as just a string.
onclick='document.getElementById('image1').click();' is the same as the string "document.getElementById('image1').click();", it does nothing.
add the line below to each anchor tag in the second row
document.getElementById('previewLink').related_id=this.id
<a onclick="if(document.getElementById(this.related_id)!=null){document.getElementById(this.related_id).click()};" id="previewLink"><img id="previewImage" src="http://i.imgur.com/UevhwuA.png"></a>
<br><br>
<a id="image1" onclick="this.related_id=this.id;document.getElementById('previewImage').src='http://i.imgur.com/UevhwuA.png';alert('1');document.getElementById('previewLink').related_id=this.id"><img src="http://i.imgur.com/UevhwuA.png"></a>
<a id="image2" onclick="this.related_id=this.id;document.getElementById('previewImage').src='http://i.imgur.com/121fy0E.png';document.getElementById('previewLink').related_id=this.id;alert('2')"><img src="http://i.imgur.com/121fy0E.png"></a>
I'd remove the inline handlers and use addEventListener() instead - except for demo purposes I've left your alert() messages in the inline onclick attributes to simulate the click behaviour that you want clicks on the preview image to mimic.
By putting the logic into JS in a <script> element you'll find it much easier to maintain because you can format the code in a readable manner.
Then simply use a variable to keep track of what the currently selected image is:
// the following JS should be in a script element at the end of the body
// and/or wrapped in a window onload handler
function imageClick(e) {
currentImage = e.currentTarget;
document.getElementById("previewImage").src = currentImage.querySelector("img").src;
}
var images = document.querySelectorAll(".image");
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("click", imageClick);
}
var currentImage = images[0]; // default to first image
document.getElementById('previewLink').addEventListener("click", function() {
currentImage.click();
});
<a id="previewLink"><img id="previewImage" src="http://i.imgur.com/UevhwuA.png"></a>
<br><br>
<a id="image1" class="image" onclick="alert('1')"><img src="http://i.imgur.com/UevhwuA.png"></a>
<a id="image2" class="image" onclick="alert('2')"><img src="http://i.imgur.com/121fy0E.png"></a>
Note also that I added a class to your lower images in order to make it easy to process them in a loop to add their click handler. This is optional, you could select by id instead with .querySelectorAll("#image1,#image2").

Using jQuery to Assign the Correct Class to an Image in an Image Swap Gallery

So, I'm using this lovely image swap fellow:
jQuery Image Swap Gallery
You can see a demo of it in action on my site here: http://hannahnelsonteutsch.com/v2/art-piece.php
The problem is, with the #main_image img
<div id="main_image" class="grid_7">
<img class="wide" src="zImages/arrows-2.jpg" />
</div>
note the class="wide". there are two classes that need to be applied dynamically to the images, once they're "swapped": "wide" and "tall", based on whether we're using an image that is in portrait or landscape.
The nice thing, which I have a hunch that a superior coder could make use of, is that the thumbnails for each image already have the correct class assigned to them:
<img class="tall" src="zImages/arrows-1.jpg" />
<img class="wide" src="zImages/arrows-2.jpg" />
<img class="wide" src="zImages/arrows-3.jpg" />
<img class="tall" src="zImages/arrows-4.jpg" />
<img class="tall" src="zImages/arrows-5.jpg" />
Here is the jQuery that is generating the image-swap:
$(document).ready(function() {
// Image swap on hover
$("#details img").hover(function(){
$('#main_image img').attr('src',$(this).attr('src').replace());
// This is my failed attempt to assign
// the correct class to the #main_img img:
$('#main_image img').attr('class',$('#details img').attr('class').replace(this));
});
// Image preload
var imgSwap = [];
$("#details img").each(function(){
imgUrl = this.src.replace();
imgSwap.push(imgUrl);
});
$(imgSwap).preload();
});
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
Note two things:
The original tutorial has this line of code:
$('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''));
which i've replaced with this:
$('#main_image img').attr('src',$(this).attr('src').replace());
the key being the .replace('thumb/', '') vs .replace().
We're using CSS to shrink the images which significantly speeds up image load times upon hover. i.e. the images have already been loaded because we're using the same image for the thumbs and main image.
my own attempt to answer this question has not worked
$('#main_image img').attr('class',$('#details img').attr('class').replace(this));
So, that's where I'm at. Anyone have any ideas to solve this ?
Thanks so much for your time.
Cheers,
Jon
You need to use the $(this) selector so jquery knows which image you are hovering over. Also you should probably use mouseenter instead of hover as you only need to verify the mouse position once. Finally, got rid of replace() in your function as that wasn't doing anything. By using attr and changing the src or class you are replacing the value automatically. Here's a draft I set up of your page: http://jsfiddle.net/AjBDg/2/
Using $('#main_image img').attr('class',$(this).attr('class')); should be enough.
See: http://jsfiddle.net/DpvFX/

unable to load image using Javascript in IE 6

I am trying to set source for Img tag using Javascript at button click. The problem which i m facing is that the I cannot see the Image in IE 6 but it works in FireFox. I browsed and tried few solutions like load the image in page load(Document load) itself or set a timer, but nothing works consistently. This problem also not consistent so unable to find the exact solution. the code goes here-
<li> <a id="lnk1" runat="server">
<img class="each_idea_icon" alt="" runat="server" id="imgAs" idea="images" />
</a>
</li>
//on button client click
var imgAs = $('#<%=imgAs.ClientID %>');
imgAs.attr("src", "../../Common/Images/EN/ABC.png");
Can somebody tell me wat could be the issue. It works perfectly in IE. I have removed ">" or "<" so code can be visible.
by default in server side i set the image src.
I too had the same problem and the below code fixed it:
var imgAs = $('#<%=imgAs.ClientID %>');
var imgParent = img.parentNode;
imgParent.innerHTML = "<img src='/_layouts/images/minus.gif' id='" + img.id + "' alt='" + img.alt + "'></img>";
I assigned the HTML string to innerHTML of its parent element.
Hope this helps!
Try using
imgAs.setAttribute ( "src" , "../../Common/Images/EN/ABC.png" );
See
element.setAttribute
Have you tried setting it first to a blank/clear gif or image file? Sometimes it has a hard time setting the img src, if it did not have an image initially.
I beleve i know what is your problem , for some reason when u use
<img ... />
insted of
<img ..> </img>
in some cases it does not work
Try an image that is not a png, ie6 and png's never played nicely. You need some ie specific code to get them to work properly.

Categories