Determing which element was clicked - javascript

I have a html like:
<div class="clicked-div" onclick="divClicked(this);">
<img src="src1"/>
<img src="src2"/>
......
</div>
if I set the img onclick event using the following method:
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onClick=imageClicked(imgs[i]);
}
function divClicked(div){
alert(div.getAttribute("id"));
}
function imageClicked(image){
alert(image.getAttribute("src"));
}
when the uiwebview load one image, it will call imageClicked a time though I haven't click it.
And when I click a image ,how do I determing which method will be called divClicked or imageClicked? THank you.

Your code is calling imageClicked at the point you're trying to just set it up as a handler.
It's actually easier than you think it is:
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = imageClicked; // <=== Not *calling*, just referring to it
}
function imageClicked() {
alert(this.getAttribute("src")); // <== `this` rather than `image`
}
When imageClicked is called in response to the click event, it's called with this set to the image element that was clicked.
How to prevent the div to handle the click event when the image was clicked
Instead of onclick, you use modern event handling and stop propagation. As you're using a uiWebView, you don't have to worry about old IE, which makes things simpler:
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("click", imageClicked, false);
}
function imageClicked(e) {
alert(this.getAttribute("src"));
e.stopPropagation(); // <=== Prevents the click reaching the div
}
Live example:
// Hook up the divs so we handle clicks on them
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].onclick = divClicked; // <=== Not *calling*, just referring to it
}
function divClicked() {
alert("div clicked");
}
// The images code
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener("click", imageClicked, false);
}
function imageClicked(e) {
alert(this.getAttribute("src"));
e.stopPropagation();
}
<div>
<img src="https://www.gravatar.com/avatar/2cd48a51689add31036ce202cc020255?s=32&d=identicon&r=PG&f=1">
</div>
<div>
<img src="https://www.gravatar.com/avatar/760b4da77fd54d37c104029ff1f56749?s=32&d=identicon&r=PG">
</div>
<div>
<img src="https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG">
</div>
<div>
No image in this one, so you can see it handle clicks
</div>
Side note: Although you can use onClick in your HTML, when you're using it in JavaScript, it has to be onclick (all lower case). I've made that change above in the version that still used it.

Related

using javascript in html to delete things when clicked

I have previously posted about this page Im trying to create and Im still running into errors. I am very new to this and getting confused. I need to use a for loop to loop over the images and assign an event listener to each one so that when they are clicked on they get deleted. Im getting confused with the difference variables and pulling the html into my javascript. I keep getting ".addEventListener is not a function" and so I keep changing things but getting lost.
<!DOCTYPE html>
<html>
<body>
<div id = 'img'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img"/>
</div>
<script text="javascript">
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++){
images[i].addEventListener("click", () => {
images[i].remove();
});
}
</script>
</body>
</html>
You are accessing array directly, which won't have the addEventListener. Try images[i].addEventListener
images.addEventListener should be images[i].addEventListener. You want to add the listener to the specific image from the array, not the array itself. Similar problem with images.remove().
First, you have same id for your container and both of your images - ID is supposed to be unique.
Second, as people already mentioned, you can not attach eventListener to array of objects.
Something like this shoud do:
let images = document.querySelectorAll("[id^='img']");
for (let i = 0; i < images.length; i++){
images.forEach(i=>{i.addEventListener("click", () => {
i.remove();
});
});
}
<div id = 'box'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img1"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img2"/>
</div>
you cannot attach an event handler to a list of images
so loop over images and for each of them
// for each image in images
image.onclick = function (e) {
e.target.parentNode.removeChild(e.target);
This will help you - https://jsfiddle.net/n5mk9Lzj/
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
images[i].remove();
});
}
You need to update your code, you are not using index inside loop.You cannot add any listener on directly to images array.
<!DOCTYPE html>
<html>
<body>
<div id = 'img'>
<img src="https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/dogs_16x9_0.jpg?itok=byPuhQjh" id="img"/>
<img src="https://www.yvr.ca/-/media/yvr/blog/2018/57_yvr_puppies_2018.jpg" id="img"/>
</div>
<script text="javascript">
let images = document.querySelectorAll("img");
for (let i = 0; i < images.length; i++){
images[i].addEventListener("click", () => {
images[i].remove();
});
}
</script>
</body>
</html>

Img src is undefined after addEventListener

I want to change a picture to a gif on mouse over, and revert it back on mouse out. But img src stays undefined after onmouseout, howerer it should be visible, because imgsrc array is an global varriable
Here is my code:
var list = document.querySelectorAll('span[data-oe-id] img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
list[i].addEventListener("mouseover",function(event)
{
console.log(imgsrc[i]); // Here it is undefined
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
list[i].addEventListener("mouseout",function(event)
{
this.src=imgsrc[i]; // Here is the same thing
});
}
Because let is brackes scope, better code will be :
var list = document.querySelectorAll('span[data-oe-id] img');
for(let i=0; i<list.length; i++){
let image = list[i];
let src = image.src;
image.addEventListener("mouseover",function(event){
console.log(src);
image.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
image.addEventListener("mouseout",function(event){
image.src=src;
});
}
Check it out and let me know.
The problem that you are having is with this. Within an event listener, this represents the event not the object calling the event.
Change this.src to list[i].src
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
to
list[i].src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
change
this.src=imgsrc[i];
to
list[i].src=imgsrc[i];

display series of images on button click

is it possible to display 3 images one after another at each button click using a array in JavaScript?
I have an array called
var images = ["image1.jpg","image2.jpg","image3.jpg"]
The way I need the website to load is for the first picture to already be there. Then when I click on the button I want the next picture to be displayed however replacing the image that was there before. I want this to repeat throughout the entire, so when I click on the button, and if the image being displayed was image3, then image1 should be displayed.
I want to share the code I have so far however I don't know where to start. the only code i have is the layout and a variable.
var images = ["image1.jpg","image2.jpg","image3.jpg"]
Try like this.Use 'document.querySelector' do select your button.On clicking button appen images using forEach in body.
var button = document.querySelector('#show');//selects your button
button.addEventListener('click',function(){ // handle click event
var images = ["image1.jpg","image2.jpg","image3.jpg"];//array of valid images
images.forEach(function(image){
img = document.createElement('img');//creates a img element
img.src = image;//sets src of img tag
document.body.appendChild(img)//appends into body
});
});
<button id="show">
Show images
</button>
Pure JS solution.
var images = ["http://placehold.it/350x150", "http://placehold.it/250x150", "http://placehold.it/150x150"];
var elem = document.getElementById('img');
var i = 0;
window.onload = function() {
elem.setAttribute("src", images[i]);
}
elem.addEventListener('click', function() {
(i < images.length-1) ? i++ : i = 0;
this.setAttribute("src", images[i]);
});
<img src='' id='img'>
jQuery solution.
var images = ["http://placehold.it/350x150", "http://placehold.it/250x150", "http://placehold.it/150x150"];
var i = 0;
$(document).ready(function() {
$('#img').attr('src', images[i]);
});
$('#img').click(function() {
(i < images.length-1) ? i++ : i = 0;
$('#img').attr('src', images[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='' id='img'>

Loop images on hover - setInterval issue

My code is running well...
but there is one thing I can't solve:
when I mouseover the image the loop starts well, but on subsequent mouseovers it starts changing faster and faster...
var Image = new Array("//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP");
var Image_Number=0;
var Image_Length= Image.length;
function change_image(num){
Image_Number = Image_Number + num;
if(Image_Number > Image_Length)
Image_Number = 0;
if(Image_Number < Image_Length)
document.slideshow.src = Image[Image_Number];
return false;
Image_Number = Image_Length;
}
function auto () {
setInterval("change_image(1)", 1000);
}
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseover="auto()" />
On every mouseover you're reassigning a brand-new-intervalâ„¢ resulting in multiple functions running at the same time.
name on IMG tag is an obsolete HTML5 attribute - See also img tag # W3.org
"change_image(1)" ...strings inside setInterval or setTimeout tigger eval. Which is bad. The real function name should be used instead: setInterval(functionName, ms)
You're not managing well the argument num
You cannot have code after a return statement
Use the mouseenter event (instead of mouseover)
and many more errors....
Here's a remake:
var images = [
"//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP"
];
var c = 0; // c as Counter ya?
var tot = images.length;
var angryCat = false;
// Preload! Make sure all images are in tha house
for(var i=0; i<tot; i++) {
var im = new Image();
im.src= images[i];
}
function changeImage() {
document.slideshow.src = images[++c%tot];
}
function auto() {
if(angryCat) return; // No more mouse enter
angryCat = true;
setInterval(changeImage, 1000);
}
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseenter="auto()" />
The increment and loop is achieved using ++c % tot
The angryCat boolean flag helps to know it the auto() already started (mouse was there!), in that case it will return; (exit) the function preventing the creation of additional overlapping intervals on subsequent mouseenter (which was your main issue).
Additionally, I'd suggest to keep your JS away from HTML, so instead of the JS attribute event
onmouseenter="auto()"
assign an ID to your image id="myimage" and use JS:
document.getElementById("myimage").addEventListener("mouseenter", auto, false);

Set css of multiple divs with same id

I have a reveal presentation in an iframe. Each slide has a div with an audio player in in and the divs id is "narration".
I have a button outside the frame that is used to hide/show this div. The problem is that it only does this for the first slide and not the rest.
EDIT : This seems to hide the divs :
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
HTML in iframe (There is one for each slide) :
<div id="narration"><p align="middle">
<audio controls="" preload="none">
<source src="mp3/2.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio></p>
</div>
JS (outside of iframe):
function checkAudio() {
if (document.getElementById('cb1').checked) {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'none';
} else {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'block';
}
}
After changing your IDs to classes (read here why), you need to update your javascript code to handle the multiple divs via a foreach loop.
function checkAudio() {
var narrationDivs = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var newDisplay = "block";
if (document.getElementById('cb1').checked) {
newDisplay = "none";
}
narrationDivs.forEach(function(div) {
div.style.display = newDisplay;
});
}
In order to have the code run again when your iframe changes, you need to update your iframe changing function:
function setURL(url){
document.getElementById('ppt').src = url;
checkAudio(); // Just run the function again!
}
If you want to show a specific element using a button, you should use a specific ID. If you want to show all items using a single button you should use classes. You could also use classes to show a specific element e.g.: The 5th button will show the 5th element but this is not a good style.
When the site in the iframe loads the next frame, your code doesn't know to hide the div it presents again. You need an event to process on.
You need to poll the id so that if it shows up again, you can hide it. See: iframe contents change event?
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
You might also want to check out the audio-slideshow plugin that allows to play separate audio files for each slide and fragment. If your main need is this, the plugin should do the job for you.
You can find a demo here and the plugin here. There is also the slideshow-recorder plugin that allows you to record your narration.
Asvin

Categories

Resources