I have a problem on swapping two images (from div vignette, to div gallerie).
Situation: I click on a little image, then It swap it place with the big image.
Here is the HTML
<div id="gallerie">
<img id="first" src="http://lorempicsum.com/futurama/620/350/2"><br/>
<div id="vignette">
<img class="second" src="http://lorempicsum.com/futurama/100/100/6">
<img class="second" src="http://lorempicsum.com/futurama/100/100/4">
<img class="second" src="http://lorempicsum.com/futurama/100/100/3">
<img class="second" src="http://lorempicsum.com/simpsons/100/100/2">
<img class="second" src="http://lorempicsum.com/simpsons/100/100/1">
<img class="second" src="http://lorempicsum.com/simpsons/100/100/4">
</div>
</div>
Here is the JavaScript
document.getElementById("vignette").addEventListener('click', changeSrc);
function changeSrc(e) {
var images = document.getElementsByClassName("second").src;
var first = document.getElementById("first").src;
s = e.target.src;
first = s;
console.log("click");
}
For the moment, I don't want to use jQuery.
Solution on some websites use images directly on the JS code with an "if" cascade. I don't think that's efficient for me.
I can propose to use a for loop with the "var image" but I don't know how to use the e.target.
I search to perform my code, so could you explain me why I was wrong?
Here is the JsFiddle
https://jsfiddle.net/ws3f4san/
I can give you more details if you want.
In this block of code, you're not actually setting the source, you're just overwriting the source you've stored as a string in the first variable.
var images = document.getElementsByClassName("second").src;
var first = document.getElementById("first").src;
s = e.target.src;
first = s;
first = s; will have no effect on the page since you're just changing a JS variable, not a dom element.
You need to edit the actual source attribute, you can do so by storing the dom element instead of the initial src value in the first variable, like so:
var images = document.getElementsByClassName("second").src;
var first = document.getElementById("first"); // Store the dom element, not the string value
s = e.target.src;
first.src = s; // Now assign the new value to the src attribute of your stored dom element
Edited having looked more thoroughly at what you're trying to do, you can swap the src's like this:
function changeSrc(e) {
// Get the initial dom element
var mainItem = document.getElementById("first");
// Save it's src before it's changed
var mainItemImage = mainItem.src;
// Get the clicked element
var clickedItem = e.target;
// Set the first image to the second image
mainItem.src = clickedItem.src;
// Set the second image to the first image's original value (which has now changed)
clickedItem.src = mainItemImage;
}
Related
I've been working with Javascript for a little bit now. My code below has various pictures defined as an object. Now I want to put these images as <img> inside <li> tags. However, I am experiencing some difficulty with this.
for (var i = 0; i < pictures.length; i++){
var newImage = document.createElement('img')
newImage.setAttribute('class', 'image-item')
newImage.setAttribute('alt', pictures[i].name)
newImage.src = pictures[i].url
var liItem = document.createElement('li')
liItem.innerHTML = newImage
document.getElementById('pictures').appendChild(liItem)
console.log(liItem)
}
Any idea on how to resolve this? The result has to look like this:
<li><img src="picture1.jpg" alt="loremipsum"></li>
Right now console tells me the following:
Change liItem.innerHTML = newImage to liItem.appendChild(newImage)
The innerHTML property sets or returns the HTML content (inner HTML) of an element. so you should change liItem.innerHTML = newImage to liItem.appendChild(newImage)
Javascript:
function Add(){
var mydiv = document.getElementById("mydiv");
var images = mydiv.getElementsByTagName("img");
var dydiv = document.createElement("div");
for (var i = 0; i < images.length; i++) {
var elem = document.createElement("img");
elem.setAttribute("src", images[i].src);
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
dydiv.appendChild(elem);
}
}
Html:
<input type="button" onclick="Add()" value="Add"/>
<div id="mydiv">
<asp:Repeater id="rpt" runat="server">
<itemtemplate>
<div >
<img src='<%#Eval("img")%>' alt="No Image" />
</div>
</temtemplate>
</asp:Repeater>
</div>
Here I'm getting the duplicate values in Images array object. As there are 4 images, I am getting 8 images.(btw I don't understand why I am getting duplicates :-( ) Now I want to remove the duplicates without sorting. plz help me....
Hope this logic to remove duplicates from an array might help. I'm not saying to copy this and paste this. I just want to share the logic, and the rest I think you can figure it out.
var items = ["milk","bottle","mobile","cups","milk","screen","table", "toothpaste"];
var filteredItems= [];
$.each(items, function(i, element){
if($.inArray(element, filteredItems) === -1) filteredItems.push(element);
});
The array :filteredItems will contain uniquevalues without sorting the original array..
Hope that serves you.
This may be because as you append images to your document, the images HTMLCollection (images) increases in size.
If I do var images = document.getElementsByTagName('img');, I get an HTMLCollection containing all the elements that I looked for.
If I then go and do:
var newImage = document.createElement('img');
document.getElementsByTagName('body')[0].appendChild(newImage);
The HTML collection now contains the new image as well.
What you may be trying to accomplish is changing the height, width and src of the image that already exists. In that case, you wouldn't have to create a new element and then append it, you could just loop over the HTMLCollection and change the height, width and src of the element in the HTMLCollection.
is it possible to give a div an Id from image title within. so that any image that is uploaded into an empty div without an id the div.id will copy the images title
using js
example pass OSCAR up to div id
<div id="">
<img src="images/image/image.png" title="OSCAR"/>
</div>
Considering this question is not tagged jQuery and all img should have a title attribute.
http://jsfiddle.net/eC3DE/
var images = document.querySelectorAll('div > img'),
i = 0,
len = images.length,
img;
for (; i < len; i++) {
img = images[i];
img.parentNode.id = img.title;
}
Please note that you will have to run the code everytime an image is added to the DOM. If you are using a modern browser that supports the MutationObserver object, you could use it to detect when new images are added.
Include jQuery and use this code for set div id:
$(function(){
$("div > img[title]").each(function(){
var parent = this.parentNode;
if(!parent.id)parent.id=this.title;//if id is empty, set id from title
})
})
Or you can take div so:
$("img[title='OSCAR']").parent("div");
I made an each function that counts the images inside a div and I am trying to set the number of images counted inside the div as a data attribute for the div but it is not working.
Have I gone about this the wrong way because it does not seem to be working?
Here is the site http://www.touchmarketing.co.nz/test/
var mostImages = 0;
numSliders = $wowSlides.length,
lastVindex = numSliders-1;
$wowSlides.each(function(){
var $this = $(this),
$images = $this.find('img'),
numImages = $images.length;
$images.css({width:$slideWidth, 'float':'left', 'position':'relative'}).wrapAll('<div class="slider" />');
$slider = $this.find(".slider");
$slider.width($slideWidth*numImages).css({'float':'left'});
$this.data('count', numImages); // add data-count="insert number here" to this .wowSlides div
console.log(numImages);
if(numImages > mostImages){
mostImages = numImages;
}
});
This sets data to jQuery's proprietary data cache:
$this.data('count', numImages);
It doesn't set to a data- attribute of the element. Generally there shouldn't be a need to set a data- attribute on the client, since its purpose is to transfer data from server to client.
Nevertheless, if you want to set it, use
$this.attr('data-count', numImages)
or
this.setAttribute('data-count', numImages)
Personally, if I wanted to associate a small amount of data with an element, I'd just store it as a property directly on the element itself.
this.count = numImages;
For primitive data, it's harmless. For larger objects or other DOM elements, I'd be more hesitant.
i want to change image using innerhtml of img tag when i click on it my code is given below
tempData +='<td >';
tempData +='<img src="'+frontImg+'" id='+ii+' onClick="flipImage(this.id);" />';//from where flipImage call
tempData +='</td>';
it works fine but it change image when it return form the function but i wanted to change it before flipImage return
function flipImage(m)
{
var jsonLen = jsonImages.images.length;
var imgNumber = finalImageArray[m];
for(jsn = 0;jsn <jsonLen ;jsn++)
{
if(jsonImages.images[jsn].imageKey== imgNumber)
{
realImage = jsonImages.images[jsn].imagePath;
var element = document.getElementById(m);
// var mg = '<img src="bool.jpg" />'; // change when this line execute what should i put here.?
//element.innerHTML=mg; want like this.
//this is actual code but it change image after returning the function so i don't want this.
element.innerHTML=realImage;
element.setAttribute('src',realImage);
element.setAttribute('onclick', '');
break;
}
}
}
so i wanted to change image before flipImage return.
this is just a sample code and
You can't use innerHTML for <img /> tags as they don't have HTML inside them, they're singletons and have no inside contents.
Just use imgElement.setAttribute('src', 'http://...'); to change the image.