Scenario: I'm trying to create a script that allows a user to click a thumbnail image and display a larger image in preview box. I'm using a div and a img for this example just as a placeholder for now.
Question In Jquery, is there a way to use a function with parameters as a callback for a onclick event listener? I've looked at addEventListener and Onclick and .on method in jquery, but nothing seems to fit what i'm searching for.
My Attempts:
http://jsfiddle.net/davideugenepeterson/9emhuzw0/3/
http://jsfiddle.net/EhtrR/931/
Javascript:
var numberOfImages = 4;
var imageArray = [];
//since i'm going to hide all other divs each time a img is clicked,
// I need to be calling from imageArray[] so I can difArray check later
for (i = 0; i <= numberOfImages; i++) {
//counting starts from zero, but frontend already built their naming convention to start with 1
if (i === 0) {
continue
}
imageArray.push(i);
}
for (i = 0; i <= imageArray.length; i++) {
if (i === 0) {
continue
}
//on each img click show corresponding div and hide all others, not working
$("#img-" + imageArray[i]).on('click', function () {
$("#div-" + i).show();
});
}
Another solution (four variations)
a)
// JavaScript
var img = document.getElementsByTagName('IMG'),
div= document.getElementsByTagName('DIV'),
current, i;
for(i = 0; i < img.length; i++){
(function(i){
img[i].onclick = function(){
div[i].style.display = 'block';
if(current) current.style.display = 'none';
current = div[i];
};
})(i);
}
b)
var img = document.getElementsByTagName('IMG'),
div= document.getElementsByTagName('DIV'),
current, i;
for(i = 0; i < img.length; i++){
(function(i){
img[i].onclick = function() { callback(i); };
})(i);
}
function callback(i){
div[i].style.display = 'block';
if(current) current.style.display = 'none';
current = div[i];
}
c)
var img = document.getElementsByTagName('IMG'),
div= document.getElementsByTagName('DIV'),
current, i;
for(i = 0; i < img.length; i++){
img[i].onclick = callback.call(this,i);
}
function callback(i){
return function () {
div[i].style.display = 'block';
if(current) current.style.display = 'none';
current = div[i];
};
}
<!-- HTML -->
<style>
div {display:none;}
</style>
<img src="01.jpg" alt="" />
<img src="02.jpg" alt="" />
<img src="03.jpg" alt="" />
<img src="04.jpg" alt="" />
<img src="05.jpg" alt="" />
<div>first</div>
<div>second</div>
<div>third</div>
<div>fourth</div>
<div>fifth</div>
Working jsBin
d) jQuery version
(function(){
var div = $('div'), current;
$('img').each(function(index){
$(this).bind ('click', function(){
$('div:nth(' + index + ')').show();
if(current) current.hide();
current = $('div:nth(' + index + ')');
});
});
})();
Working jsBin
I don't understand what you're trying to do with an array. Give the image something relating to a corresponding element you want to be shown (I used data attribute in example).
And give a collective class name to all the elements that are going to be shown/hidden.
Then on click, hide all and show the one related to what was clicked.
$('img').click(function(){
$('.somename').hide();
$('#div-'+$(this).data("number")).show();
});
See fiddle: fiddle
Related
i'm new here.
I'm trying to change the height of my pictures when I click on them, and then when I click them again they return to the original height. I'm trying to do this by using a the same CSS class, a for-loop and an if/else.
My image html is this several times:
var element = document.getElementsByClassName("imgclasstosize");
for(var i = 0; i < element.length; i++) {
var element = element[i];
element.onclick = function() {
if (element.style.height == "500px") {
element.style.height = "200px";
} else {
element.style.height = "500px";
}
}
}
<img class="imgclasstosize" src="https://assets.picspree.com/variants/FRgeQ4d3pFXszVF7QW9VBgFQ/f4a36f6589a0e50e702740b15352bc00e4bfaf6f58bd4db850e167794d05993d">
<img class="imgclasstosize" src="https://assets.picspree.com/variants/RXCuAnyzqoapjkZQuhDFwBMs/f4a36f6589a0e50e702740b15352bc00e4bfaf6f58bd4db850e167794d05993d">
I can only do the behavior I want for the first image. All others don't do the same.
Can you please help me know what I'm doing wrong?
Thanks in advance
You could select all Elements using querySelector, you can also keep getElementsByClassName().
Then loop through each image and add event listener:
var element = document.querySelectorAll('.imgclasstosize');
element.forEach(el => {
el.addEventListener('click', function(event) {
if (event.target.style.height == '500px') {
event.target.style.height = '200px';
} else {
event.target.style.height = '500px';
}
});
});
<img class="imgclasstosize" src="https://assets.picspree.com/variants/FRgeQ4d3pFXszVF7QW9VBgFQ/f4a36f6589a0e50e702740b15352bc00e4bfaf6f58bd4db850e167794d05993d">
<img class="imgclasstosize" src="https://assets.picspree.com/variants/RXCuAnyzqoapjkZQuhDFwBMs/f4a36f6589a0e50e702740b15352bc00e4bfaf6f58bd4db850e167794d05993d">
You're accessing the element the wrong way. Use the built in event, like this:
var element = document.getElementsByClassName("imgclasstosize");
for(var i = 0; i < element.length; i++) {
var element = element[i];
element.onclick = function(event) {
if (event.target.style.height == "500px") {
event.target.style.height = "200px";
} else {
event.target.style.height = "500px";
}
}
}
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.
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/
I'm looking for a way to replace an image that could be used anywhere on a page.
So if we have an example html page like this:
<html>
<head>
</head>
<body>
<img id="1" src="example.com/img/1889.png">
<div style="background: url('example.com/img/1889.png')">
<div>
<a>
<img id="2" src="example.com/img/1889.png">
</a>
</body>
</html>
Where ever - example.com/img/1889.png - appears, it must be replaced with something else.
EDIT
Unfortunately I can't use any javascript libraries. Its for a browser plugin. Nor can I use browser specific APIs
There might be some syntax errors here, but basically just try something like:
<script>
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].src == "oldImg")
imgs[i].src = "newImg";
}
}
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].style.backgroundImage == "oldImg")
divs[i].style.backgroundImage = "newImg";
}
}
</script>
The following code does what you're looking for:
var images = document.querySelectorAll('[src]'), // all image and input elements
styled = document.querySelectorAll('[style]'), // all elements with inline style
iLen = images.length,
sLen = styled.length,
url = 'example.com/img/1889.png', // the string you're searching for
str = 'some/string', // replace with whatever you choose
i;
// check for 'example.com/img/1889.png' in image source
for (i = 0; i < iLen; i += 1) {
if (images[i].src.indexOf(url) !== -1) {
images[i].src = str;
}
}
// check for 'example.com/img/1889.png' in either background or background-image
for (i = 0; i < sLen; i += 1) {
if (styled[i].style.backgroundImage.indexOf(url) !== -1) {
styled[i].style.backgroundImage = 'url(' + str + ')';
}
}
Demo
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 );
}
}
};