I have the following html:
<li>
<a href=\"p://emotion/appreciate\" onclick=\"flip()\">
<img src=\"smile.png\" />
</a>
</li>
Basically, I want the flip function to replace the src of the img enclosed in it to smile-inactive when pressed, and change it back again to smile.png if it's now already in smile-inactive.png. How can I do this without having to do document.getElementById if I don't want to give the img an id?
Inside your flip function, I would make sure that this points to the anchor you just clicked, then grab the img as the first childNode:
<a href=\"p://emotion/appreciate\" onclick=\"flip.call(this)\">
function flip(){
var img = this.children[0];
if (/smile\.png/.test(img.src))
img.src = "smile-inactive.png";
else
img.src = "smile.png"
}
EDIT
As #am not i am points out, you can achieve a slight gain in browser support by switching
var img = this.children[0];
to
var img = this.getElementsByTagName("img")[0];
Take both images, merge them to one, and just use offset to determine which one is shown.
You can do it by simply by CSS.
Related
I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.
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
I am building a lightbox, in pure JavaScript. I currently have my images loading via AJAX, but i know it is easier to just have the img data-src attribute being replaced onclick to src.
I however have NO idea how this is done in pure JavaScript, by that i mean, without using any libraries.
Can anyone tell me how this is done?
to sum up: How do i change ex:
<img data-src="URL"/>
to:
<img src="URL"/>
without jQuery.
You can do it like shown below:
var imgEl = document.getElementsByTagName('img');
for (var i=0; i<imgEl.length; i++) {
if(imgEl[i].getAttribute('data-src')) {
imgEl[i].setAttribute('src',imgEl[i].getAttribute('data-src'));
imgEl[i].removeAttribute('data-src'); //use only if you need to remove data-src attribute after setting src
}
}
The above code will fetch all img tags, check if they have a data-src attribute and if present, replace it with src.
Demo Fiddle
Get a handle on the image element, and then set it's src property, using the value from getAttribute().
Plain Javascript doesn't have any helper functions to handle data-* attributes, it just treats them as any other attribute.
var img = document.getElementById("myimg");
img.src = img.getAttribute("data-src");
You can use forEach with querySelectorAll
var imageElements = document.querySelectorAll('img');
imageElements.forEach(c=> c.setAttribute('src',c.getAttribute('data-src')));
img{width:100px;}
<img data-src='https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png' />
I'm replacing one image with another in javascript, then adding a link to it, but it doesn't seem to be working. Any suggestions?? Please and thank you!!
function showImage2(){
document.getElementById("tbc").src = "images/s2.jpg";
var elem = document.getElementById("Slideshow");
elem.style.display = "none";
document.getElementById('tbc').style.display='block';
document.getElementById('tbc').style.usemap='ss2Map';
var link = document.createElement('a'); // create the link
link.setAttribute('href', 'wastewater.html'); // set link path
link.appendChild("images/s2.jpg"); // append to link
}
link.appendChild("images/s2.jpg"); // append to link
This line won't do anything. You can only append an element, not a text string. You need to append document.getElementById("tbc") instead if I understand your markup correctly.
If that's not what you're trying to append, you can use var el = document.createElement('img') to create an img tag and then set the src attribute using el.setAttribute('src','images/s2.jpg')
After this, the above line would become link.appendChild(el); which would work.
I think all you really need is to have one image with a link and one image without the link. Onload, the image without the link is shown and the other image with the link is hidden. Once click on a button or something, then hide the image without the link and show the image with the link correct?
<img id="image1" src="http://us.123rf.com/400wm/400/400/tonygers/tonygers1108/tonygers110800022/10200687-manipulated-nasa-photographs-of-the-earth-and-moon-isolated-together-on-a-black-background.jpg" />
<a style="display:none;" id="image2" href="http://www.google.com" target="_blank"><img src="http://d1jqu7g1y74ds1.cloudfront.net/wp-content/uploads/2011/08/us-astronaut-bruce-mccandless-space-walk.jpg" /></a>
Click Me
<script>
function showImage2(){
var imageOne = document.getElementById('image1');
var imageTwo = document.getElementById('image2');
imageTwo.style.display = 'block';
imageOne.style.display = 'none';
}
</script>
You can see the working code here. http://jsfiddle.net/QbbJU/1/
appendChild() can only take a DOM node, not a string.
To set the text of an element, you can either set innerHTML or textContent, or append a text node (from document.createTextNode())
You also probably want to put the link somewhere in your page.
Is there a way to create an imagemap on an image when the image is created in Javascript?
So image is created this way:
var img = new Image();
then set all properties.
But how do I now create an imagemap on this image?
Regards,
Tony
UPDATE
Here's my code to create image:
function createimg()
{
var img = new Image();
img.src='Image/URL';
img.alt='Next image';
img.id = 'span1';
img.style.zIndex = 10;
img.style.position = 'absolute';
img.style.display='none';
img.style.top = '130px';
img.style.padding='10px';
img.style.left='440px';
img.usemap='#trialmap';
img.className ='dynamicSpan';
document.body.appendChild(img);
return img;
}
This sits in inside tags. Now imagemap:
<map name="trialmap">
<area shape ="rect" coords ="0,0,500,500"
href ="http://www.google.com" target ="_blank" alt="Sun" />
<area shape ="circle" coords ="100,100,10,10"
href ="http://www.twitter.com" target ="_blank" alt="Mercury" />
</map>
Now where do I put this, cause it has to be right beneath the image, per what I have read? I cannot put it inside a tag, cause that does not work.
First,
How do you create an image in Javascript?
But on to your question...
An image map is tied to the <img /> element, not the actual image itself. So even if you have a method for creating an image in javascript, how are you placing that image in the page?
If the image is being pushed to the server and therefore has a URL, you could then create an img element in the DOM, and then make your image map.
In fact, you could even have the image map before the image was ever created, since all that ties the map to the image is the attribute usemap which points to the name attribute of the map element.
Quick Edit
I think I understand now. The Image() method you are referring to is simply creating an img element, right?
So basically, you just need to add the attribute/property usemap and set it to the name of the <map> you want to use.
To use David's method, you would go with something like:
//This assumes the image will go in some div with the id of "image-box"
var imageBox = getElementById("image-box");
var myImage = createElement("img");
myImage.id = "myImage";
myImage.src = "myimage.png";
myImage.useMap = "#myImageMap";
imageBox.appendChild(myImage);
//Now you would need to have a map element with a name of myImageMap
var myMap = createElement("map");
myMap.name = "myImageMap";
imageBox.appendChild(myMap);
//Obviously you would want to then fill the map using the appendChild method with the area elements that make it useful...
http://www.w3.org/TR/html4/struct/objects.html#h-13.6 explains the HTML structure. You just need to build that structure directly in DOM instead of in HTML.
The Opera WSC has a good introduction to DOM in it.