How to get image src for each div with same structure? - javascript

I have multiple same structure div with images. And now I am trying to get src of the image which is clicked.
I have multiple divs with structure like this:
<div id="modal" class="model">
<img id="image" src= "<%= loop.url %>">
<div class="container">
<%- loop.title %>
</div>
</div>
I am trying to get src of the image of the div which is clicked. I am trying the following code for this:
document.querySelectorAll('.model').forEach(function(item) {
item.addEventListener('click', function() {
modal.style.display = "block";
captionText.innerHTML = document.getElementById("image").src;
});
});
But this only gives my src of the first image for all, and not for each image.
I am new to front end development, and I would appreciate any help.
document.querySelectorAll('.model').forEach(function(item) {
item.addEventListener('click', function() {
modal.style.display = "block";
captionText.innerHTML = document.getElementById("image").src;
});
});
<div id="modal" class="model">
<img id="image" src= "<%= loop.url %>">
<div class="container">
<%- loop.title %>
</div>
</div>

You can use querySelector to retrieve the first img element in the .modal div.
querySelector works like you might be used to from css. E.g.
element.querySelector("img") selects the first with tag <img>
element.querySelector(".someclass") selects the first with a class
element.querySelector("#someid") selects an element with an id
document
.querySelectorAll(".modal")
.forEach(
el => el.addEventListener(
"click",
event => {
const img = el.querySelector("img");
if (img) console.log(img.src);
}
)
);
<div class="modal">
<img src="src1.jpg">
<p>Image 1</p>
</div>
<div class="modal">
<img src="src2.jpg">
<p>Image 2</p>
</div>
<div class="modal">
<img src="src3.jpg">
<p>Image 3</p>
</div>
<div class="modal">
<img src="src4.jpg">
<p>Image 4</p>
</div>

Try this:
$("img").click(function(){
captionText.innerHTML = $(this).attr('src');
});
This will work if you have Jquery. If you don't, add this script to your HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

You can retrieve the img src as below:
$(document).on('click', '.modal', function(event)
{
console.log($(this).find('img').attr("src"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal">
<img src="src1.jpg" alt="im1">
<p>Image 1</p>
</div>
<div class="modal">
<img src="src2.jpg" alt="im2">
<p>Image 2</p>
</div>
<div class="modal">
<img src="src3.jpg" alt="im3">
<p>Image 3</p>
</div>
<div class="modal">
<img src="src4.jpg" alt="im4">
<p>Image 4</p>
</div>

I tried to see if I can run getElementById on item but it doesn't have such function. It does have getElementsByTagName so you can reference the img elements inside item
let captionText = document.getElementById('captionText')
document.querySelectorAll('.model').forEach(function(item) {
let currentSrc = item.getElementsByTagName('img').item(0).src
item.addEventListener('click', function(x) {
captionText.innerHTML = currentSrc;
});
});

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>

How to change a dynamic button text

Created 3 dynamic divs(sea_p,sea_p_div,div_btns), inside the third(div_btns) created 2 buttons
how can i change the text inside these dynamic buttons before adding to body?
let div = $(`<div class="Search_div"></div>`)
let p = $(`
<div class="sea_p">
<div class="sea_p_div">
<div class="p_img">
<img src="" alt="" width="80" />
<div class="div_span">
<span class="p_name"></span>
<span class="p_surname"></span>
</div>
</div>
<div class="div_btns">
<button class="req_btn req_check1" data-id="">Text1</button>
<button class="req_btn req_check2" data-id="">Text2</button>
</div>
</div>
</div>`)
div.append(p)
//change text here
$('body').append(div)
let div = $(`<div class="Search_div"></div>`)
let p = $(`
<div class="sea_p">
<div class="sea_p_div">
<div class="p_img">
<img src="" alt="" width="80" />
<div class="div_span">
<span class="p_name"></span>
<span class="p_surname"></span>
</div>
</div>
<div class="div_btns">
<button class="req_btn req_check1" data-id="">Text1</button>
<button class="req_btn req_check2" data-id="">Text2</button>
</div>
</div>
</div>`)
div.append(p)
//change text here
p.find(".req_check1").html('New Text');
p.find(".req_check2").html('New Text 2');
$('body').append(div)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Please try this.
window.onload = function() {
$(".req_check1").html('New Text');
$(".req_check2").html('New Text 2');
}
Thank you.
You can use text() method of jQuery, on the jQuery object of button whose text you want to change.
NOTE : Use it just after appending the p tag to the body.
var buttonWrap = $('.sea_p .div_btns button');
buttonWrap.eq(0).text("Text for button 1");
buttonWrap.eq(1).text("Text for button 2");

Accessing multiple elements by getElementsByClassName() with JS

I am trying to create multiple popups on one page that would appear after clicking a button corresponding to them. I currently have them under the same class, as in here:
<div>
<!-- Popup -->
<div class="popup">
<div class="popup-content">
Some text here
</div>
</div>
<!-- Button -->
<img src="button.png" class="popup-button"/>
</div>
The problem is that I am struggling to access individual elements with my javascript code. I am not sure what to replace the manual array accessing ( [0] right now ) with.
<script>
// Get the popup
var popup = document.getElementsByClassName("popup")[0];
// Get the button that opens the popup
var btn = document.getElementsByClassName("popup-button")[0];
// When the user clicks the button, open the popup (hidden by default)
btn.onclick = function() {
popup.style.display = "block";
}
</script>
Now, I could create multiple scripts and access the arrays manually for each element but of course I am trying to automate it, so that script would run depending on which button was clicked. Say, if 5th button was clicked, 5th popup appears. Thank you!
Best way to link multiple elements in Javascript is using an id through the dataset of the elements.
// Get the popup's btn list
var popupsBtn = document.getElementsByClassName("popup-btn");
// Go through the popup's btn list
for (var i = 0; i < popupsBtn.length; i++) {
// Define the onclick event on popup's btn
popupsBtn[i].onclick = function() {
// Get the popup associated to the btn with the data-popup-id
var popup = document.getElementById("popup-" + this.dataset.popupId);
// Use a class to toggle popup visible or not
popup.classList.toggle("visible");
}
}
.popup {
display: none;
}
.popup.visible {
display: block;
}
<!DOCUMENT html>
<html>
<head></head>
<body>
<div>
<div id="popup-1" class="popup">popup 1 here</div>
<img src="button.png" class="popup-btn" data-popup-id="1" />
</div>
<div>
<div id="popup-2" class="popup">popup 2 here</div>
<img src="button.png" class="popup-btn" data-popup-id="2" />
</div>
<div>
<div id="popup-3" class="popup">popup 3 here</div>
<img src="button.png" class="popup-btn" data-popup-id="3" />
</div>
</body>
</html>
Given your HTML, it would probably be easiest to just access the previous sibling of the clicked button to get to the .popup, and then change its style:
document.querySelectorAll('.popup-button').forEach(button => {
button.onclick = () => {
button.previousElementSibling.style.display = 'block';
};
});
.popup {
display: none;
}
<div>
<div class="popup">
<div class="popup-content">
Some text here1
</div>
</div>
<img src="button.png" class="popup-button" />
</div>
<div>
<div class="popup">
<div class="popup-content">
Some text here2
</div>
</div>
<img src="button.png" class="popup-button" />
</div>
<div>
<div class="popup">
<div class="popup-content">
Some text here3
</div>
</div>
<img src="button.png" class="popup-button" />
</div>
You can use other attributes to identify the button. You could not rely on the className alone.
You can use data-id attribute and pass it in the method. using this.
Depending on your HTML structure, there are multiple possibilities.
Anyway, I suggest you to use .querySelectorAll() to get your elements, and then use a .forEach() to execute your code.
I tried to use much of your code to make it work correctly.
With a parent div
// Get all the buttons that opens the popups
var btns = document.querySelectorAll(".popup-button");
btns.forEach(function(btn, index) {
// When the user clicks the button, open the popup that is in the same parent div
btn.onclick = function() {
btn.closest('div').querySelector('.popup').style.display = "block";
}
});
.popup {
display: none;
}
<div>
<div class="popup">
<div class="popup-content">Pop-up 1</div>
</div>
<img src="button.png" class="popup-button" />1
</div>
<div>
<div class="popup">
<div class="popup-content">Pop-up 2</div>
</div>
<img src="button.png" class="popup-button" />2
</div>
<div>
<div class="popup">
<div class="popup-content">Pop-up 3</div>
</div>
<img src="button.png" class="popup-button" />3
</div>
Without a parent div
// Get the popups
var popups = document.querySelectorAll(".popup");
// Get the buttons that opens the popups
var btns = document.querySelectorAll(".popup-button");
btns.forEach(function(btn, index) {
// When the user clicks the button, open the popup (hidden by default)
btn.onclick = function() {
popups[index].style.display = "block";
}
});
.popup {
display: none;
}
<div class="popup">
<div class="popup-content">Pop-up 1</div>
</div>
<img src="button.png" class="popup-button" />
<br>
<br>
<div class="popup">
<div class="popup-content">Pop-up 2</div>
</div>
<img src="button.png" class="popup-button" />
<br>
<br>
<div class="popup">
<div class="popup-content">Pop-up 3</div>
</div>
<img src="button.png" class="popup-button" />
This solution withour parent div will work even if the popups and the buttons are not next to each other. But the order (and index) of the elements need to be the same. See it here:
// Get the popups
var popups = document.querySelectorAll(".popup");
// Get the buttons that opens the popups
var btns = document.querySelectorAll(".popup-button");
btns.forEach(function(btn, index) {
// When the user clicks the button, open the popup (hidden by default)
btn.onclick = function() {
popups[index].style.display = "block";
}
});
.popup {
display: none;
}
<img src="button.png" class="popup-button" />1
<img src="button.png" class="popup-button" />2
<img src="button.png" class="popup-button" />3
<div class="popup">
<div class="popup-content">Pop-up 1</div>
</div>
<div class="popup">
<div class="popup-content">Pop-up 2</div>
</div>
<div class="popup">
<div class="popup-content">Pop-up 3</div>
</div>
Hope it helps.

how to add variable in the img src html tag

<script>
var domain_name="www.abc.com"
</script>
<div id="tp_otherinfo" style="top: 558px;">
<div class="cls_footerImg" id="divFooterMainqqqq">
<div id="footerimgDiv1">
<img src=domain_name+"/images/place1a.svg"><span id="id_places" class="clsFooterHead">1 Places</span></div>
<div class="footerimgDiv2">
<img src=domain_name+"/images/calendara.svg"><span id="id_days" class="clsFooterHead">3 Days</span></div>
<div class="footerimgDiv2">
<img src=domain_name+"/images/photos1a.svg"><span id="id_photos" class="clsFooterHead">8 Photos</span></div>
<div class="footerimgDiv2">
<img src=domain_name+"/images/reviews1a.svg"><span id="id_review" class="clsFooterHead">7 Reviews</span></div>
<div class="footerimgDiv2">
<img src=domain_name+"/images/timea.svg"><span id="id_date" class="clsFooterHead">6th February 2014</span></div>
</div>
</div>
I want to add a variable in img src.
I have many img src like this ..i cant keep on changing the domain change so i wanted to add a variable in place of relative image path
You can use below work around to replace your domain_name for src attributes.
First correct your markup and put src value with domain_name in double quotes like below
<img src="domain_name/images/place1a.svg">
Use jQuery to replace all domain_name with variable value -
<script>
var domain_name="www.abc.com"
$(function(){
$('#tp_otherinfo').find('img').each(function(){
var srcpath = $(this).attr('src');
srcpath = srcpath.replace('domain_name',domain_name);
$(this).attr('src',srcpath);
});
});
</script>
If you are using Razor Engine you can write it like this:
#{ string domain_name = "www.abc.com"; }
....
<img src="#domain_name/images/etc."
Here is for php language. You can write your div in html, and inside img tag place like this.
<?php echo "http://" . $_SERVER['SERVER_NAME'] ."and here you add your image.png or whatever" ?>
try this :
<script>
//have an array with all the domains
var domain_names = ["domain1.com", "domain2.com", "domain3.com", "domain4.com", "domain5.com", "domain6.com", "domain7.com"];
//now set them
$(document).ready(function () {
var i = 0;
$("#tp_otherinfo img").each(function () {
var src = $(this).attr('src');
src = domain_names[i] + src;
$(this).attr('src', src);
i++;
});
});
</script>
<div id="tp_otherinfo" style="top: 558px;">
<div class="cls_footerImg" id="divFooterMainqqqq">
<div id="footerimgDiv1">
<img src="/images/place1a.svg"><span id="id_places" class="clsFooterHead">1 Places</span>
</div>
<div class="footerimgDiv2">
<img src="/images/calendara.svg"><span id="id_days" class="clsFooterHead">3 Days</span>
</div>
<div class="footerimgDiv2">
<img src="/images/photos1a.svg"><span id="id_photos" class="clsFooterHead">8 Photos</span>
</div>
<div class="footerimgDiv2">
<img src="/images/reviews1a.svg"><span id="id_review" class="clsFooterHead">7 Reviews</span>
</div>
<div class="footerimgDiv2">
<img src="/images/timea.svg"><span id="id_date" class="clsFooterHead">6th February 2014</span>
</div>
</div>
</div>

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