How can I apply a function to several images in jQuery? - javascript

I need a little help with (probably) something really simple.
I want to use a script which converts images from color to grayscale.
I got it working partially — the first image turns gray, but the second won’t.
I know this is because an id cannot be used multiple times:
var imgObj = document.getElementById('grayimage');
I tried this:
var imgObj = $(’.grayimage’)[0];
But it didn’t work. Changing it to getElementByClass also does not work. (Before people ask, I did change the id to class in the <img> tag.)
I really could use some help here. Thanks in advance!

$('.grayimage').each(function(idx,imgObj){
<do your code here>
});

$('.grayimage') gives you a list of all elements with grayimage as a class. If you add '[0]' you're accessing the first element, so any changes you make will apply to only the first image that it finds with this class.
You should loop through all elements:
var images = $('.grayimage');
for(i = 0; i < images.length; i++) {
var image = images[i];
// Do stuff
}

Related

How to swap <div> elements by using "mouseover" event?

let wrapperSt = document.querySelector(".wrapper");
for(i=0; i<100; i++){
let divGroup = document.createElement('div');
wrapperSt.append(divGroup);
divGroup.className= 'pixel';
divGroup.textContent= '';
}
I've created the div element called "pixel" by using loop because, i need couple hundreds of them. (I'll use them as a little boxes that could change color)
But, i want these boxes ("pixel" div) to turn brown and sustain (style.backgroundColor ="brown";)
So, i created another div that will replace the previous div ("pixel").
let selectPx = document.getElementsByClassName("pixel");
selectPx.addEventListener("mouseover", function(){
let pxChange = createElement("div");
//This is where i got stuck!
})
I could not finish my code, i found it a bit complicated even if it is probably something very simple.
Any suggestions or piece of information would be very helpful. Thank you.
Not sure exactly what you are trying to do... I think you are trying to change the color of the div that your mouse is over? If so, you have a couple of issues with your code. Instead of adding the event listener to the list of divs, you need to add it to each one individually. Also, you should only need to change the background color of each element instead of creating a new one each time.
let selectPx = document.querySelectorAll(".pixel");
selectPx.forEach(pixel => {
pixel.addEventListener("mouseover", () => {
pixel.style.backgroundColor = "brown";
});
});
I'm not sure why you have to create a new div inside the first one. In your code, when you trigger the mouseover event you can get the div under the mouse and apply the style to it:
let selectPx = document.getElementsByClassName("pixel");
selectPx.addEventListener("mouseover", function(evt){
let divUnderMouse = evt.target;
divUnderMouse.style.backgroundColor ="brown";
})
I haven't tried it but it should work

How to make a photo appear when clicking on another photo? Javascript, DOM

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.

Random image with javascript doesnt want to give the src

I want to show a random picture with every refresh but I don't know why my code is not working... probably because I'm bad at javascript, haha.
I tried "3" instead of "imgs.length", but it's still not working - I too don't really want to give an exact number, because the image count may vary.. only for my example I use three images.
var imgs = ['img1','img2','img3'];
function getRandomImage(){
var rnd = Math.floor(Math.random()*imgs.length);
document.getElementById('pr_randImage').src = imgs[rnd];
}
</script>
<img id="pr_randImage">
Quellcode is just not showing any src at all for the img. What am I doing wrong? I'm thankful for every help.
change this
var imgs = ['img1','img2','img3'];
to something like this depending on extension of the image you are using
var imgs = ['img1.png','img2.png','img3.jpg'];
If that still doesn't work then you need to include the path of where the images are
Something like this
document.getElementById('pr_randImage').src = "/images/" + imgs[rnd];

Get DOM Element with jQuery

I have a web page that is structured like this:
<canvas id="myCanvas"></canvas>
#for(var i=0; i<10; i++) {
<div class="my-element">
<canvas></canvas>
</div>
}
This code generates one main canvas. Below it, 10 other dynamically generated divs are being generated. In reality, this loop is just used to show that I have some code being dynamically generated. The main thing to understand is the my-element piece.
In my javascript, I have the following:
$(function() {
var mainCanvas = document.getElementById('myCanvas');
initializeCanvas(mainCanvas); // This works.
var dynamicElements = $('.my-element');
for (var i=0; i<dynamicElements.length; i++) {
initializeCanvas($(dynamicElements[i])[0]); // This does not work
}
});
function initializeCanvas(canvas) {
// do stuff
}
The first call to initializeCanvas works because I'm passing in an actual HTML Dom element. But the second initializeCanvas, which is called multiple times, fails because it's passing in something else. How do I get the same type of element as what's returned by document.getElementById in this case?
Thanks!
First of all, this doesn't make sense:
$(dynamicElements[i])[0]
You are getting jQuery element, unwrapping it, then wrapping again in jQuery...
what you simply need to do is get canvas from the element
dynamicElements.eq(i).find('canvas')[0] should do the job
You can't use the same element for this purpose. I suggest you to clone it. Like;
var dynamicElements = $('.my-element').clone();
Also when you add more element with my-element class this will be messy. You should make sure to select only one element with $('.my-element') selection.

Relative images broken, need javascript fix

new here. I have no access to most of the source files on my website, so I am trying to fix some broken images on page load with javascript.
When I use the inspect element for one of these broken images it shows like this:
<img src="-82.jpg" width="60px">
when they should be
<img src="http://example.com/files/images/-82.jpg" width="60px">
This is for bunch of different images, -82.jpg, -2482.jpg, -3582.jpg
Here's what I have tried so far. This seems to work but for some reason it breaks other javascript on the page.
html
<script type="text/javascript" src="http://example.com/files/js/fiximages.js"></script>
<body onload="fixImages();">
my fiximages.js file
function fixImages() {
var toReplace = '<img src="-';
var replaceWith ='<img src="http://www.example.com/files/images/-';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
I'm a bit of a noob so I also need to know how to link the html to the javascript to get it to load when the page loads. Thanks guys.
This should solve your problem:
function fixImages() {
// Create a list of all img which src starts with "-".
var imgs = document.querySelectorAll('img[src^="-"]');
// Loop through this list.
for (var i = 0; i < imgs.length; i++) {
// For each img, replace its src with the correct path + the
// src that's already there.
imgs[i].setAttribute('src', 'http://www.example.com/files/images/' + imgs[i].getAttribute('src'));
}
}
Demo
Welcome to SO!
The problem in your approach is that changing the body's pure HTML is never a good idea for a dynamic page. Also, javascript's replace, when used without a regex, is going to replace only the first ocurrence of the string.
Now, when you need to change an element's attribute, Javascript has a manipulation called DOM. There are plenty material and tutorials on the web... You should look into it!
http://www.w3.org/TR/DOM-Level-2-Core/introduction.html
http://www.w3schools.com/jsref/dom_obj_document.asp
With DOM, you can select an element as a variable, and manipulate its properties and attributes, so, in your case it would be:
function fixImages() {
var imgs = document.getElementsByTagName("img");
for(var i=0; i<imgs.length; i++) {
if(imgs[i].src.indexOf("-") == 0)
imgs[i].src = "http://www.example.com/files/images/" + imgs[i].src;
}
}

Categories