var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "img/mutantpre.jpg");
pic3.setAttribute("onclick", "display()");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
Im trying to create a function to set all pictures to hidden when this one is clicked. However from that function I dont know which one was clicked. How do i figure out which one they clicked get the id of it so i can set the visibility of the other ones.
var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "img/mutantpre.jpg");
pic3.setAttribute("onclick", "display('mutantpre')");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
by passing same id in function of on click you can do this trick
You can also do like this
var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "#");
pic3.setAttribute("onclick", "display()");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
function display(){
el = document.getElementsByTagName("img");
for(var i =0;i<el.length;i++){
el[i].addEventListener("click",function(e){
alert("the clicked one's id is "+e.target.id);
});
}
}
Check the working Fiddle
Hope this helps!
var images = document.getElementsByTagName('img');
var activeImage = images[0]; // Assuming the first image is active at first
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function() {
activeImage.classList.remove("active");
this.classList.add("active");
activeImage = this;
}
}
The display function :
function display(element){
var list = document.getElementsByTagName("img");
for(var i=0; i<list.length ; i++){
list[i].style.opacity = "0";
}
element.style.opacity="1";
}
And in your code you must have this :
pic3.setAttribute("onclick", "display(this)");
Live example
http://jsfiddle.net/W65yA/1/
Related
I would dynamically add the onmouseover and onmouseout attributes to each anchor in my html page when the page loads.
I tried in all the ways I know but I can not get it to work.
HTML
<body onload="init()">
JAVASCRIPT
function init(){
startTimers();
initLinksProperties();
}
function initLinksProperties(){
var onMouseOverColor = 'red';
var onMouseOutColor = '#00BFFF';
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
links[i].onmouseover = function(){ cambiaColore(i, onMouseOverColor); };
links[i].onmouseout = function(){ cambiaColore(i, onMouseOutColor); };
}
}
function cambiaColore(index, color){
var element = document.links[index];
element.style.color = color;
}
I also tried with:
links[i].onmouseover = cambiaColore(i, onMouseOverColor);
links[i].onmouseout = cambiaColore(i, onMouseOutColor);
links[i].addEventListener('onmouseover', cambiaColore(i, onMouseOverColor));
links[i].addEventListener('onmouseout', cambiaColore(i, onMouseOutColor));
links[i].setAttribute('onmouseover', cambiaColore(i, onMouseOverColor));
links[i].setAttribute('onmouseout', cambiaColore(i, onMouseOutColor));
cambiaColore is a function that changes the color of the link.
I have no syntax errors but nothing happens.
Where am I wrong?
When trying your code I had "Cannot read property 'style' of undefined" error in this function :
function cambiaColore(index, color){
var element = document.links[index];
element.style.color = color;
}
seems like "document.links[index]" doesn't return your element.
So I change your function a bit, instead of having index as first argument you have the element itself.
function cambiaColore(element, color){
element.style.color = color;
}
And in mouseover and mouseout functions I pass the element as first argument :
function initLinksProperties(){
var onMouseOverColor = 'red';
var onMouseOutColor = '#00BFFF';
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
links[i].onmouseover = function(e){ cambiaColore(e.target, onMouseOverColor); };
links[i].onmouseout = function(e){ cambiaColore(e.target, onMouseOutColor); };
}
}
entire code :
function init() {
startTimers();
initLinksProperties();
}
function initLinksProperties(){
var onMouseOverColor = 'red';
var onMouseOutColor = '#00BFFF';
var links = document.getElementsByTagName("a");
console.log(links);
for(var i = 0; i < links.length; i++){
links[i].onmouseover = function(e){ cambiaColore(e.target, onMouseOverColor); };
links[i].onmouseout = function(e){ cambiaColore(e.target, onMouseOutColor); };
}
}
function cambiaColore(element, color){
element.style.color = color;
}
document.links is not accessible in cambiaColore. Pass the element or the event so you can retrieve the target you want to change. Right now you're trying to change undefined.
(function(window, document, undefined)
{
initLinksProperties();
})(window, window.document);
function initLinksProperties(){
var onMouseOverColor = 'red';
var onMouseOutColor = '#00BFFF';
var links = document.getElementsByTagName("a");
for(var i = 0; i < links.length; i++){
links[i].addEventListener('mouseover',
function(event)
{
var element = event.target;
cambiaColore(element, onMouseOverColor);
}, false);
links[i].addEventListener('mouseout',
function(event)
{
var element = event.target;
cambiaColore(element, onMouseOutColor);
}, false);
}
}
function cambiaColore(element, color){
element.style.color = color;
}
Link 1
Link 2
Link 3
Link 4
Link 5
When the function cambiaColore() is called, the value of the i variable has changed because the loop already finished. You don't need to pass index or element as others have suggested. You just need to use event.target:
function cambiaColore(index, color) {
// no need to use index or element. You can remove it.
event.target.style.color = color;
}
Link for the complete solution: https://jsfiddle.net/h6xhajtd/
If you want to know more about event.target: https://developer.mozilla.org/en/docs/Web/API/Event/target
I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}
Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />
var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.
I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.
This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".
Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">
Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.
I have 2 arrays, an image array and a price array.
I have the images displaying, but I'd like to display the price, which at the moment I have held in the image name, when I mouseover the image, is it possible?
HTML
<section id=main>
<!--populate with images from array-->
<p id="photos" class="product_display">
<script>getImage();</script>
</section>
JS
//image array for products
var imageArray = new Array();
imageArray[0]="images/coffee_prod_1.png";
imageArray[1]="images/coffee_prod_2.png";
imageArray[2]="images/coffee_prod_3.png";
imageArray[3]="images/coffee_prod_4.png";
imageArray[4]="images/coffee_prod_5.png";
imageArray[5]="images/coffee_prod_6.png";
imageArray[6]="images/coffee_prod_7.png";
//price array for products
var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"];
function getImage(){
var container = document.getElementById("photos");
for (var i=0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
img.name = priceArray[i];
container.appendChild(img);
}
}
I thought I might be able to add something like 'img.onmouseover = imageMouseOver(priceArray[i]);' to my getImage function, and then have something inside the function that would display the image name (ideally over the image) on mouseover. I was hoping to apply an opaque colour too so the image name might be clearer.
Any help would be appreciated!
I would suggest creating a container div for each photo, and in each container add your and like another div that contains the price. Set the price divs hidden at first with display:none or something, and then in your javascript add some listeners to show and hide it:
for (var i=0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
var container = document.createElement("div");
var price = document.createElement("div");
price.innerHTML = priceArray[i];
//Style your price and image elements so they fit in the container and the price is displayed over the image etc
container.appendChild(price);
container.appendChild(img);
container.onmouseover = function() {
container.getElementByClass("price").style.display = "block";
};
container.onmouseout = function() {
container.getElementByClass("price").style.display = "none";
};
}
You may need to fiddle with the onmouseover/out events a bit if showing the price div messes it up i.e. onmouseover is called on the layer with the highest z index instead of container, I haven't tried it but this should give you a rough idea
Working example here:
http://jsfiddle.net/0vts5291/
HTML
<section id=main>
<!--populate with images from array-->
<p id="photos" class="product_display">
</section>
JS
var imageArray = new Array();
imageArray[0]="images/coffee_prod_1.png";
imageArray[1]="images/coffee_prod_2.png";
imageArray[2]="images/coffee_prod_3.png";
imageArray[3]="images/coffee_prod_4.png";
imageArray[4]="images/coffee_prod_5.png";
imageArray[5]="images/coffee_prod_6.png";
imageArray[6]="images/coffee_prod_7.png";
//price array for products
var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"];
function getImage() {
var container = document.getElementById("photos");
for (var i = 0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
img.name = priceArray[i];
img.title = priceArray[i];
container.appendChild(img);
}
}
getImage();
I want to get the id of the image the mouse hovers. But I do not understand how to get the ID. Can some one help me :). TY!
function placeImage(x){
var div = document.getElementById("thumbnails");
div.innerHTML = ""; // clear images
for (var i =0; i <= x; i++) {
var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.position="relative";
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);
}
};
With the placeImage function i place the images. Now I want to add an mouse event and change the class of the image who is targeted.
<div id="thumbnails" onmouseover="mouseOver(this);" ></div>
I added a mouse over to all the thumbnails. But I cannot get the id of the image of which the mouse hovers. I want to call the id or change the image.className of that particlair image. But I do not know how to call it. Now it only alerts "thumbnial"
function mouseOver(e){
alert(e.id);
}
Use this keyword:
<div id="thumbnails" onmouseover="mouseOver(this);" ></div>
function mouseOver(e){
alert(e.id);
}
Edit from the comments:
var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.mouseover = mouseOver;
image.position="relative";
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);
}
Note the mouseOver function being called when the image is hovered. this will refer to the image element and not the div.
To get the id of an image when you hover over it, try this:
function placeImage(x){
var div = document.getElementById("thumbnails");
div.innerHTML = ""; // clear images
for (var i =0; i <= x; i++) {
var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.position="relative";
image.onmouseover = mouseOver; // <-- Added this
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);
}
}
function mouseOver(e) {
alert(this.id);
}
Hope this helps, though I'm not sure about it working on a dynamically added image.
document.ready = function () {
var thumbnails = document.getElementById("thumbnails");
var imgs = thumbnails.getElementsByTagName("img");
for( var i=0; i<imgs.length; i++ ) {
imgs[i].onmouseover = function() {
alert( this.id );
}
}
};