Get index of child element which has been clicked - javascript

I want to attach event listener to all img-frame classes and I get which element (by index) inside the parent has been clicked:
$('.img-frame').each((i, img) => {
$(img).on('click', pictureClicked);
});
function pictureClicked(e) {
console.log(e.currentTarget)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="three-image-container">
<img class="img-frame" src="blob:https://localhost:4000/daf31145-292d-462c-bc94-aad0610b2972">
<img class="img-frame" src="blob:https://localhost:4000/8e4a143e-f9f0-47ec-a361-4e571bb49d1a">
<img class="img-frame" src="blob:https://localhost:4000/c8236624-571d-4386-9225-e14e7fac9560">
</div>
So if the first one has been clicked I want 0 and ...
How can I do this?

You want to delegate the event to save on handlers:
$('.three-image-container').on('click', 'img', pictureClicked);
function pictureClicked(e) {
console.log($(e.target).index())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="three-image-container">
<img class="img-frame" src="blob:https://localhost:4000/daf31145-292d-462c-bc94-aad0610b2972">
<img class="img-frame" src="blob:https://localhost:4000/8e4a143e-f9f0-47ec-a361-4e571bb49d1a">
<img class="img-frame" src="blob:https://localhost:4000/c8236624-571d-4386-9225-e14e7fac9560">
</div>

I think it should help you :)
$('.img-frame').each((i, img) => {
$(img).on('click', pictureClicked);
});
function pictureClicked(e) {
console.log($(e.currentTarget).index())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="three-image-container">
<img class="img-frame" src="blob:https://localhost:4000/daf31145-292d-462c-bc94-aad0610b2972">
<img class="img-frame" src="blob:https://localhost:4000/8e4a143e-f9f0-47ec-a361-4e571bb49d1a">
<img class="img-frame" src="blob:https://localhost:4000/c8236624-571d-4386-9225-e14e7fac9560">
</div>

Related

Problems with toggling more than one Image when clicking

I have my code set so that an image can change after clicking the image. I understand getElementById is meant to get results from one class name, but I don't know how to expand on that, and have the same result without changing the class name. I tried querySelector, but I think I am missing something. Any help would be appreciated. Here is my code:
<!--how do I make this apply to all images?-->
function changeImage() {
let displayImage = document.querySelector('#img-area, #star-picture, #colorful')
if (displayImage.src.match('Kabuto.jpg')) {
displayImage.src = 'PersonalCreations/LylatForce.jpg'
} else {
displayImage.src = 'Kabuto.jpg'
}
}
<!--image area or main img-->
<div class="row">
<div class="column">
<img id="img-area" src='Kabuto.jpg' class="responsive" alt="" onclick="changeImage()" height="200" with="200">
<button class="first" onclick="document.getElementById('img-area').src='PersonalCreations/LylatForce.jpg'">Change Image</button>
</div>
<div class="column">
<img id="star-picture" src="Kabuto.jpg" height="200" with="200" />
<button onclick="document.getElementById('star-
picture').src='PersonalCreations/Year6969.jpg'">Change Image</button>
</div>
<div class="column">
<img id="colorful" src="Kabuto.jpg" height="200" with="500" />
<button onclick="document.getElementById('colorful').src='PersonalCreations/BallInTheShoeProductions.jpg'">Change Image</button>
</div>
<div class="column">
<img id="holiday" src='Kabuto.jpg' alt="" onclick="changeImage()" height="200" with="200">
<button onclick="document.getElementById('holiday').src='PersonalCreations/ChristmasFestivalProject.jpg'">Change Image</button>
</div>
</div>
<p>Hello World</p>
<script src="imgchanger.js"></script>
First, CSS styling and JavaScript should not be used inline with HTML. You should separate out those things.
Your issue is that you have:
let displayImage = document.querySelector ('#img-area, #star-picture, #colorful')
But, .querySelector() will only return the first matching element. You need .querySelectorAll(), which will return a collection of all matching elements.
Or, you can avoid all of that and do this:
// Set up a single event handler for all clicks in the document
document.addEventListener("click", function(evt){
// But test to see if the click originated at a button
if(evt.target.nodeName === "BUTTON"){
// Get the button's parent div and then the source of the first img within that
let img = evt.target.closest("div").querySelector("img").src;
// Find out which button was clicked by looking at its class
switch (evt.target.className){
case "first":
// Change the source
img = "PersonalCreations/LylatForce.jpg";
break;
case "second":
img = "PersonalCreations/Year6969.jpg";
break;
case "third":
img = "PersonalCreations/BallInTheShoeProductions.jpg";
break;
case "fourth":
img = "PersonalCreations/ChristmasFestivalProject.jpg";
break;
}
console.clear();
console.log("Image source is now: " + img);
}
});;
.img200x200 { height:200px; width:200px; }
.img200x500 { height:200px; width:500px; }
<!-- See how much cleaner the HTML is now that the CSS and
JavaScript have been separated out? -->
<div class="row">
<div class="column">
<img src="Kabuto.jpg" class="responsive img200x200" alt="">
<button class="first">Change Image</button>
</div>
<div class="column">
<img src="Kabuto.jpg" class="responsive img200x200" alt="">
<button class="second">Change Image</button>
</div>
<div class="column">
<img src="Kabuto.jpg" class="responsive img200x500" alt="">
<button class="third">Change Image</button>
</div>
<div class="column">
<img src="Kabuto.jpg" class="responsive img200x200" alt="">
<button class="fourth">Change Image</button>
</div>
</div>
<p>Hello World</p>

Hide and show images on hover

jQuery(document).ready(function(){
jQuery(".artists-main .artists-name1 a ").mouseover(function(){
jQuery(".artists-image .artists-img1").show();
});
jQuery(".artists-main .artists-name1 a ").mouseout(function(){
jQuery(".artists-image .artists-img1").hide();
});
jQuery(".artists-main .artists-name2 a ").mouseover(function(){
jQuery(".artists-image .artists-img2").show();
});
jQuery(".artists-main .artists-name2 a ").mouseout(function(){
jQuery(".artists-image .artists-img2").hide();
});
jQuery(".artists-main .artists-name3 a ").mouseover(function(){
jQuery(".artists-image .artists-img3").show();
});
jQuery(".artists-main .artists-name3 a ").mouseout(function(){
jQuery(".artists-image .artists-img3").hide();
});
jQuery(".artists-main .artists-name4 a ").mouseover(function(){
jQuery(".artists-image .artists-img4").show();
});
jQuery(".artists-main .artists-name4 a ").mouseout(function(){
jQuery(".artists-image .artists-img4").hide();
});
});
.artists-image img{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="artists-main">
<div class="artists-name1">Artist 1</div>
<div class="artists-name2">Artist 2</div>
<div class="artists-name3">Artist 3</div>
</div>
<div class="artists-image">
<img class="artists-img1" src="https://picsum.photos/200/300?random=1">
<img class="artists-img2" src="https://picsum.photos/200/300?random=2">
<img class="artists-img3" src="https://picsum.photos/200/300?random=3">
</div>
Hide and show images on hover. Class artists-main has artists names and class artists-image has images of the artists. It's working fine but my code is lengthy. I have round about 50+ artists and page will be filled by jQuery code. I want to shorten it.
use same class name
$.each($(".artists-main .artists-name a"), function(index, element) {
$(element).mouseover(function() {
$('.artists-image .artists-img:eq(' + index + ')').show();
})
$(element).mouseout(function() {
$('.artists-image .artists-img:eq(' + index + ')').hide();
})
})
.artists-image img{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="artists-main">
<div class="artists-name">Artist 1</div>
<div class="artists-name">Artist 2</div>
<div class="artists-name">Artist 3</div>
</div>
<div class="artists-image">
<img class="artists-img" src="https://picsum.photos/200/300?random=1">
<img class="artists-img" src="https://picsum.photos/200/300?random=2">
<img class="artists-img" src="https://picsum.photos/200/300?random=3">
</div>
You can also use native javascript code:
let images = document.querySelectorAll(".artists-img");
images.forEach(x => x.classList.add("no-display"));
function changeHover(idx) {
images.forEach(x => x.classList.add("no-display"));
document.getElementById("img" + idx).classList.remove("no-display");
}
.no-display {
display: none;
}
<div class="artists-main">
<div class="artists-name"><a onmouseover="changeHover(1)" href="#">Artist 1</a></div>
<div class="artists-name"><a onmouseover="changeHover(2)" href="#">Artist 2</a></div>
<div class="artists-name"><a onmouseover="changeHover(3)" href="#">Artist 3</a></div>
</div>
<div class="artists-image">
<img class="artists-img" id="img1" src="https://i.picsum.photos/id/474/536/354.jpg?hmac=wmJxGqF8CZdMBSMLHMqolt46tKerJulEfjVeecZJHyE">
<img class="artists-img" id="img2" src="https://i.picsum.photos/id/266/536/354.jpg?hmac=sWDqtbQOm-fz6eG3de_B6hdMz4PpEHoxp0qn2v-C9gQ">
<img class="artists-img" id="img3" src="https://i.picsum.photos/id/573/536/354.jpg?hmac=DLmhMwWbQZVtjZxUi5BvgENG7DfyeVxKcBdEKHIQ9k8">
</div>
Fiddle snippet
You can use the index of the element, and control visibility by adding CSS class:
jQuery(document).ready(function(){
jQuery(".artists-main > div").mouseover(function(){
var current_index = $(this).index();
$('.artists-image > div').removeClass('visible-artist');
$('.artists-image > div').eq(current_index).addClass('visible-artist');
});
});
.artists-image > div.visible-artis {
display: none;
}
using index() and avoiding to number your class:
$(".artists-main .artists-name a").on("mouseover mouseout", function(e){
var index = $(this).closest('div').index();
if(e.type == "mouseover"){
$(".artists-image .artists-img").eq(index).show();
}
else{
$(".artists-image .artists-img").eq(index).hide();
}
});
.artists-image img{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="artists-main">
<div class="artists-name">Artist 1</div>
<div class="artists-name">Artist 2</div>
<div class="artists-name">Artist 3</div>
</div>
<div class="artists-image">
<img class="artists-img" src="https://picsum.photos/200/300?random=1">
<img class="artists-img" src="https://picsum.photos/200/300?random=2">
<img class="artists-img" src="https://picsum.photos/200/300?random=3">
</div>
This is a no effort solution. But I really recommand that you settle this up with pure CSS (pseudo-elements).
CSS = Presentation
JS = Behaviour
$(document).ready(function () {
$('.artists-name1').hover(function() {
$('.artists-img1').toggle();
});
$('.artists-name2').hover(function() {
$('.artists-img2').toggle();
});
$('.artists-name3').hover(function() {
$('.artists-img3').toggle();
});
});
.artists-image img{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="artists-main">
<div class="artists-name1">Artist 1</div>
<div class="artists-name2">Artist 2</div>
<div class="artists-name3">Artist 3</div>
</div>
<div class="artists-image">
<img class="artists-img1" src="https://picsum.photos/200/300?random=1">
<img class="artists-img2" src="https://picsum.photos/200/300?random=2">
<img class="artists-img3" src="https://picsum.photos/200/300?random=3">
</div>
The SIMPLEST way to do this would be using purely CSS, you may follow the example given here :
.artists-img1 {
display : none;
}
.artists-name1:hover + .artists-img1 {
display: block
}
<div class="artists-main">
<div class="artists-name1">Artist 1</div>
<div class="artists-name2">Artist 2</div>
<div class="artists-name3">Artist 3</div>
</div>
<div class="artists-image">
<img class="artists-img1" src="https://picsum.photos/200/300?random=1">
<img class="artists-img2" src="https://picsum.photos/200/300?random=2">
<img class="artists-img3" src="https://picsum.photos/200/300?random=3">
Solution reference :
https://www.w3schools.com/howto/howto_css_display_element_hover.asp
.hide {
display: none;
}
.myDIV:hover + .hide {
display: block;
color: red;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Display an Element on Hover</h2>
<div class="myDIV">Hover over me.</div>
<div class="hide">
<img src="https://images.unsplash.com/photo-1580820726687-30e7ba70d976?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1500&q=80" id="picture2" width="20%" height="auto" /></div>
</body>
</html>

How to add a class in Javascript/jQuery if an element has content in it?

I am working on a website in which I want to check whether element has any content in it.
Below is my html code. I have mentioned condition#1 where opacity-pointseven class should be added through script if classes featured-block__title and featured-block__tag have content in it.
<div class="featured-block">
<a href="/" class="featured-block__item cf">
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src=""> // (condition#1, where opacity-pointseven needs to be added)
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
</a>
</div>
Problem Statement:
I tried in the following way, but it doesn't seem to work properly.
<script>
jQuery(function ($) {
if ($(this).find(".featured-block__title").not(":empty") && $(this).find(".featured-block__tag").not(":empty")) {
$(this).find(".img-fit img").addClass("opacity-pointseven"); // For condition#1
}
});
})
</script>
You can loop over parent div and find the child items and then add the class over there.
Here in the example, I am getting $('.featured-block__item-inner') as a parent and then finding items inside it.
$('.featured-block__item-inner').each(function() {
if ($(this).find(".featured-block__title").not(":empty").length > 0 && $(this).find(".featured-block__tag").not(":empty").length > 0) {
$(this).find(".img-fit img").addClass("opacity-pointseven"); // For condition#1
} else {
$(this).find(".img-fit img").addClass("default-opacity");
}
})
.opacity-pointseven {
width: 100px;
height: 100px;
}
.default-opacity {
width: 50px;
height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="featured-block">
<a href="/" class="featured-block__item cf">
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src="">
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src="">
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title"></h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
</a>
</div>
i hope the following script will heplful.
jQuery(function ($) {
if ($(".featured-block__title").text().length != 0 && jQuery('.featured-block__tag').text().length != 0 ) {
$(".img-fit img").addClass("opacity-pointseven"); // For condition#1
}
});
I think you can edit a bit in your code
.not(":empty") to .html()
<script>
jQuery(function ($) {
if ($(this).find(".featured-block__title").html() && $(this).find(".featured-block__tag").html()) {
$(this).find(".img-fit img").addClass("opacity-pointseven"); // For condition#1
}
});
})
</script>
<div class="featured-block">
<a href="/" class="featured-block__item cf">
<div class="featured-block__item-inner">
<figure class="featured-block__image img-fit">
<img src=""> // (condition#1, where opacity-pointseven needs to be added)
</figure>
<div class="featured-block__content">
<h1 style="margin-bottom:0px;" class="featured-block__title">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h1>
<h1 class="featured-block__tag"> More Coverage</h1>
</div>
</div>
</a>
</div>
<script>
jQuery(function ($) {
if ($(".featured-block__title").html() != undefined && $(".featured-block__title").html() != "" && $(".featured-block__tag").html() != undefined && $(".featured-block__tag").html() != "") {
$(".featured-block__tag").addClass("opacity-pointseven"); // For condition#1
}
});
})
</script>
Above is changes with your provided code.
in jquery you can find classes or Ids directly without using this object.
this is only required where you are in looping of some specific element (ie. inside Div loop).

How to get this code to move one class at a time

So I have three DIVs with the same carousel effect. I am pretty sure I can use three different JavaScript codes to move one at a time but would like to make it as minimal code as possible. With the current code, when I click on the arrow once, all three of them moves. How can I get them to move separately?
There's three of the same one as the one below:
(function ($) {
$.fn.thumbGallery = function (settings) {
var $this = $(this);
return this.each(function () {
settings = jQuery.extend({
speed: 1000,
leftArrow: $this.find('.arrow-left'),
rightArrow: $this.find('.arrow-right'),
galleryContainer: $this.find('.gallery-inner'),
visibleImagesSize: 4
}, settings);
var imgElements = settings.galleryContainer.find('img').length;
var size = settings.visibleImagesSize;
//settings.leftArrow.hide();
if (imgElements > settings.visibleImagesSize) {
settings.rightArrow.show();
} else {
//settings.rightArrow.hide();
}
function animateLeft() {
var el = settings.galleryContainer.children(":last");
settings.galleryContainer.animate({
left: '+=' + el.outerWidth(true) + 'px'
},
settings.speed);
}
function animateRight() {
var el = settings.galleryContainer.children(":first");
settings.galleryContainer.animate({
left: '-=' + el.outerWidth(true) + 'px'
},
settings.speed);
}
function checkArrows() {
if (size === settings.visibleImagesSize) {
//settings.leftArrow.hide();
} else {
settings.leftArrow.show();
}
if (size === imgElements) {
//settings.rightArrow.hide();
} else {
settings.rightArrow.show();
}
}
settings.leftArrow.click(function () {
animateLeft();
size--;
checkArrows();
});
settings.rightArrow.click(function () {
animateRight();
size++;
checkArrows();
});
});
};
})(jQuery);
$(document).ready(function () {
$('.gallery').thumbGallery();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="open-space">
<h2>Open Space</h2>
<p class="description">Desk space in an open shared office environment that can be used in various of ways.</p>
<center>
<div class="gallery">
<div class="arrow-left">
<div class="arrow-left-small">
</div>
</div>
<div class="gallery-outer">
<div class="gallery-inner">
<div class="gallery-tmb">
<img src="images/openspace1.png" alt="Open Space1" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace2.png" alt="Open Space2" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace3.png" alt="Open Space3" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace4.png" alt="Open Space4" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace5.png" alt="Open Space5" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace6.png" alt="Open Space6" height="auto" width="250"/>
</div>
</div>
</div>
<div class="arrow-right">
<div class="arrow-right-small">
</div>
</div>
</div>
<span class="btn_margin">
<asp:Button ID="Button3" runat="server" Text="More lists" CssClass="btn btn-primary top" OnClick="Btn_More_Click" />
</span>
</center>
</div>
The reason they move together is because you use the .gallery selector when you call thumbsGallery(), which applies to all elelements that have class="gallery" in the HTML code. What you can do is to simply add a unique id to each of the gallery and call thumbsGallery() with each of the selectors.
HTML:
<div class="gallery" id="executive_gallery">
...
</div>
<div class="gallery" id="conference_gallery">
...
</div>
<div class="gallery" id="open_gallery">
...
</div>
Javascript:
$(document).ready(function () {
$('.gallery#executive_gallery').thumbGallery();
$('.gallery#conference_gallery').thumbGallery();
$('.gallery#open_gallery').thumbGallery();
});
JSFiddle: https://jsfiddle.net/3qeLumkp/1/

how to hide the element using jquery when clicked outside the element

Till now I can grab the src of the image and display it in a fixed division, kind of like a pop up. But I want to hide the div element when the mouse is clicked outside the div. Please guide me how to do it, and also please correct me if my code can be improved. Thanks!
js:
$(document).ready(function () {
$(".pic").hide();
$(".screen").click(function () {
display($(this));
});
});
function display($this) {
var source = $("img", $this).attr("src");
$(".pic img").attr("src",source);
$(".pic img").css("width","450px");
$(".pic").show();
}
html:
<div id="album">
<div class="pic">
<img src="" />
</div>
<div class="screen">
<h1 class="title">Photo 1</h1>
<img src="images/1 png.png" class="image" />
<p class="description">This is a description</p>
</div>
<div class="screen">
<h1 class="title">Photo 1</h1>
<img src="images/2 png.png" class="image" />
<p class="description">This is a description</p>
</div>
<span class="clear_left"></span>
</div>
blur event of jquery can be used
$(".screen").bind('blur',function () {
hide($(this));
});
function display($this) {
$(".pic").hide();
}
Try like this
$(document).click(function () {
if ($(this).class != "pic") {
$(".pic").hide();
}
});
Live Demo

Categories

Resources