I have three image tags when I click one of the images in the webpage I don't it want to disappear it but when I dblclick I want it to disappear.
let img = document.querySelectorAll("img");
console.log(img)
let c = Array.from(img);
console.log(c);
c.forEach(function(imgs) {
imgs.addEventListener("click", function(e) {
let d = imgs;
d.addEventListener("dblclick", function(v) {
console.log(img)
// I want this eventlistener to make it disapear
document.querySelectorAll("image").innerHTML = "";
})
})
})
After I read your post again I have made some changes to my answer!
const imgs=document.querySelectorAll("img");
imgs.forEach(function(img){
img.addEventListener("dblclick", function(){
this.remove();
});
});
.box {
width: 220px;
padding: 20px;
background-color: #eee;
}
<div class="box">
Click the Image to remove it !
<br>
<img src="https://via.placeholder.com/200x200" style="width: 100%">
<br><br>
<img src="https://via.placeholder.com/200x200" style="width: 100%">
</div>
This works. Above answer works too.
let img = document.querySelectorAll("img");
console.log(img)
let c = Array.from(img);
console.log(c);
c.forEach(function(imgs) {
imgs.addEventListener("dblclick", function(e) {
imgs.style.display = "none";
})
})
<img src="https://via.placeholder.com/200x200" width=150 height=150>
Related
I made this favImages array and added some image objects to it. Then I am trying to append a paragraph element(removeButton) to each of them which will be triggered by clicking the images.
var favImages = new Object();
for (var i = 0; i < 5; i++) {
favImages[i] = document.getElementById("fav" + (i + 1));
}
var removeButton = document.createElement("p");
removeButton.id = "removebutton";
removeButton.innerHTML = "Remove Image";
for (var i = 0; i < 5; i++) {
var newImage = document.getElementById(favImages[i].id);
newImage.addEventListener("click", function() {
newImage.appendChild(removeButton)
}, false);
}
Don't use a loop. Use an event listener on the container and test what was clicked using event.target. You cannot add a child to an image
You COULD use a div, put the image as a background and the span to click as content
Anyway here are some examples
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("div").remove()
})
#container div {
width: 200px
}
.remove {
float: right
}
<div id="container">
<div>
<span class="remove">X</span>
<img src="https://via.placeholder.com/150/0000FF/000888?text=image1" />
</div>
<div>
<span class="remove">X</span>
<img src="https://via.placeholder.com/150/FF00FF/000888?text=image2" />
</div>
<div>
<span class="remove">X</span>
<img src="https://via.placeholder.com/150/FF0000/000888?text=image3" />
</div>
</div>
From an array:
const images = [
"https://via.placeholder.com/150/0000FF/000888?text=image1",
"https://via.placeholder.com/150/FF00FF/000888?text=image2",
"https://via.placeholder.com/150/FF0000/000888?text=image3"
];
const container = document.getElementById("container");
container.innerHTML = images.map(img => `<div><span class="remove">X</span>
<img src="${img}" /></div>`).join("");
container.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("div").remove()
})
#container div {
width: 200px
}
.remove {
float: right
}
<div id="container">
</div>
I have three images and two anchor tags. When user click on any link then user can select any image.Then this image must be replaced with anchor tag image in which user clicked.
var control3 = document.getElementById('control1').src;
var control4 = document.getElementById('control2').src;
function getImage(e) {
fullpath = e.children[0].src;
var filename = fullpath.replace(/^.*[\\\/]/, '');
var imageSrc = filename.split("\.")[0] + ".png";
if (control1 !== fullpath) {
document.getElementById('control1').src = "images/" + imageSrc;
}
if (control2 !== fullpath) {
document.getElementById('control2').src = "images/" + imageSrc;
}
if (control3 !== fullpath) {
document.getElementById('control3').src = "images/" + imageSrc;
}
}
<img onclick="getImage(this);" src="images/image1.png" alt="">
<img onclick="getImage(this);" src="images/image2.png" alt="">
<img onclick="getImage(this);" src="images/image3.png" alt="">
<img id="control1" src="">
<img id="control2" src="">
You've really only implemented part of the process here. You need to consider the flow of the program more carefully:
You need firstly to handle click events on the links.
And you also need to make it possible for users to click on an image to select it for replacement.
Then your code needs to be able to match the clicked image to the clicked link, so it knows what change to make.
N.B. in this demo I've replaced your inline event handlers with unobtrusive event handlers using addEventListener (i.e. declared in the JS, not embedded in the HTML).
//variables to hold program state
var selectEnabled = false;
var selectedImage = "";
//handle clicks on links
var links = document.querySelectorAll(".imageLink");
links.forEach(function(lnk) {
lnk.addEventListener("click", enableImageSelection);
});
function enableImageSelection(e) {
e.preventDefault(); //stop the hyperlink doing its normal job (i.e. moving to another page)
selectEnabled = true;
alert("Please select an image to replace");
imageSrc = this.querySelector("img").src;
}
//handle clicks on the replaceable images
var clickableImages = document.querySelectorAll(".clickableImage");
clickableImages.forEach(function(img) {
img.addEventListener("click", loadImage);
});
function loadImage() {
if (selectEnabled == true) {
console.log("replacing " + this.src + " with " + imageSrc);
this.src = imageSrc;
selectEnabled = false; //image is not clickable again until a link is clicked first.
}
}
<img class="clickableImage" src="images/image1.png" alt="1" />
<img class="clickableImage" src="images/image2.png" alt="2" />
<img class="clickableImage" src="images/image3.png" alt="3" />
<br/><br/>
<img src="images/image4.png"> Click me
<img src="images/image5.png"> Click me
I don't fully understand what you want from your explanation but I guess it's something like this:
Have lots of images and two empty "boxes".
Click on a box and you can click on an image.
The box will update when you clicked on the image.
optional: make it dynamic, so you can add any amount of images or "boxes".
In order to do so you need to:
Know what box you first clicked on.
Tell the images you can select between that they can be clicked.
Update the original box with the clicked image.
bonus: give the user feedback (highlights).
var selectedImageId = ""; // 1. Know what box you first clicked on.
const SELECTABLE_CLASS_NAME = 'selectable';
// 1. Know what box you first clicked on.
function selectImage(imageElement) {
let selectableImagesContanier = document.getElementById('selectables');
if (selectedImageId && selectedImageId != imageElement.id) {
let prevSelectedImage = document.getElementById(selectedImageId);
prevSelectedImage.classList.remove(SELECTABLE_CLASS_NAME);
}
selectedImageId = imageElement.id;
// 4. bonus: give the user feedback (highlights)
imageElement.classList.add(SELECTABLE_CLASS_NAME);
selectableImagesContanier.classList.add(SELECTABLE_CLASS_NAME);}
function getImage(imageElement) {
let selectableImagesContanier = document.getElementById('selectables');
// 2. Tell the images you can select between that they can be clicked.
if (selectableImagesContanier.classList.contains(SELECTABLE_CLASS_NAME)) {
let imageToBeUpdated = document.getElementById(selectedImageId);
// 3. Update the box with the clicked image.
imageToBeUpdated.src = imageElement.src;
// 4. bonus: give the user feedback (highlights)
selectableImagesContanier.classList.remove(SELECTABLE_CLASS_NAME);
imageToBeUpdated.classList.remove(SELECTABLE_CLASS_NAME);
imageToBeUpdated.classList.add('image-shown');
}
}
img {
width: 50px;
height: 50px;
border: 2px solid;
border-color: transparent;
}
#selectables.selectable > img,
img.selectable {
border-color: lightblue;
cursor: pointer;
}
.selected-image-container {
margin-top: 1rem;
}
.selected-image-container > img {
cursor: pointer;
background-color: lightgrey;
}
.selected-image-container > img.image-shown {
background-color: transparent;
}
<div id="selectables">
<img onclick="getImage(this)" src="https://picsum.photos/id/21/50/50" alt="">
<img onclick="getImage(this)" src="https://picsum.photos/id/31/50/50" alt="">
<img onclick="getImage(this)" src="https://picsum.photos/id/41/50/50" alt="">
</div>
<div class="selected-image-container">
<img id="control1" src="" onclick="selectImage(this)">
<img id="control2" src="" onclick="selectImage(this)">
</div>
I know the question of closing a pop-up by clicking outside of it has been asked before. I have a somewhat complex pop-up and the solution offered by Phillip Walton isn't working for me.
His code simply made my page blurry but stopped the popup from appearing.
$(document).on('click', function(event) {
if (!$(event.target).closest('.maincontainer').length) {
popup.classList.remove('popup--open');
popup.style.display = 'none';
popupAccessory.style.display = 'none';
popupAccessory.classList.remove('popup--accessory--open');
maincontainer.classList.remove('blurfilter');
}
});
I also tried:
window.addEventListener('click', function(event) {
if (event.target != popup) {
popup.classList.remove('popup--open');
popup.style.display = 'none';
popupAccessory.style.display = 'none';
popupAccessory.classList.remove('popup--accessory--open');
maincontainer.classList.remove('blurfilter');
}
}, true);
This closes the popup when I click anywhere, including on the popup itself. I want it to close only when I click on part of the screen that isn't the popup.
The code to open the popup:
function openpopup() {
popup.style.display = 'initial';
setTimeout(function(){
popup.classList.add('popup--open');
popup.style.boxShadow = '0 0 45px 2px white';
maincontainer.classList.add('blurfilter')}, 10);
for (let i = 0; i < listitems.length; i++ ) {
setTimeout(function() {
listitems[i].classList.add('visible');
}, 100);
}
}
I added the event listener to a button
popupOpenbtn.addEventListener('click', openpopup);
The HTML structure:-
<div class="maincontainer>
...all my page content...
</div>
<div class="popup">
...popup contents...
</div
I would suggest using only css classes to style your popup and use JS only to add, remove and toggle that class. Not sure how close to your working exercise is this fiddle but I've prepared this to show how the document/window click event can be checked to successfully open/close the popup window.
var popupOverlay = document.querySelector('#popup__overlay');
var popupOpenButton = document.querySelector('#popupOpenButton');
var popupCloseButton = document.querySelector('#popupCloseButton');
var mainContainer = document.querySelector('main');
function closestById(el, id) {
while (el.id != id) {
el = el.parentNode;
if (!el) {
return null;
}
}
return el;
}
popupOpenButton.addEventListener('click', function(event) {
popupOverlay.classList.toggle('isVisible');
});
popupCloseButton.addEventListener('click', function(event) {
popupOverlay.classList.toggle('isVisible');
});
mainContainer.addEventListener('click', function(event) {
if (popupOverlay.classList.contains('isVisible') && !closestById(event.target, 'popup__overlay') && event.target !== popupOpenButton) {
popupOverlay.classList.toggle('isVisible');
}
});
#popup__overlay {
display: none;
background-color: rgba(180, 180, 180, 0.5);
position: absolute;
top: 100px;
bottom: 100px;
left: 100px;
right: 100px;
z-index: 9999;
text-align: center;
}
#popup__overlay.isVisible {
display: block;
}
main {
height: 100vh;
}
<aside id="popup__overlay">
<div class="popup">
<h2>Popup title</h2>
<p>
Lorem ipsum
</p>
<button id="popupCloseButton">Close popup</button>
</div>
</aside>
<main>
<div class="buttonWrapper">
<button id="popupOpenButton">Open popup</button>
</div>
</main>
I am trying to show images on a link click and hiding that image if clicked outside. After trying so many solutions for this I have came up with like below code.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center" onclick="javascript:setImageVisible('popup1', false)">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
</div>
The above code is working fine. But when I add other image like below, its not working. When I clicked outside then images are not hiding.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
$(document).click(function() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
});
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div id="Btn8"></div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Can anyone please suggest what should I do ?
You don't need jQuery to do this.
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
function hideAll() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
}
function click(e) {
e.stopImmediatePropagation();
var id, el = this;
while (el) {
el = el.nextSibling;
if (el.nodeName === 'IMG') { // finds the next sibling img element
id = el.id;
el = null;
}
}
hideAll(); // hide all images
setImageVisible(id, true); // show the right one
};
document.addEventListener('click', hideAll);
var btns = document.querySelectorAll('.btn'),
i = 0,
len = btns.length;
for (; i < len; i++) {
btns[i].addEventListener('click', click);
}
img {
width: 100px;
height: 100px;
border: 1px solid black;
}
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div class="btn" id="Btn7">Image 1</div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div class="btn" id="Btn8">Image 2</div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Sure, as you have added a tag jquery, I am asking you to do it in a simple way like this:
Snippet:
$(function () {
$(".imgPreview").hide();
$(".unstyled li a").click(function () {
$(".imgPreview").show().find("img").attr("src", $(this).attr("href"));
return false;
});
$("body").click(function () {
$(".imgPreview").hide();
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
body {margin: 10px;}
li {margin: 5px;}
.unstyled, .imgPreview {float: left; width: 50%;}
.unstyled, .imgPreview img {max-width: 100%;}
p {margin: 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Click on a link to show the respective image. Click outside to hide it!</p>
<p>Also you can right click and open it to open the image in a new tab!</p>
<ul class="unstyled">
<li>350x150</li>
<li>750x150</li>
<li>350x150</li>
<li>100x100</li>
<li>350x150</li>
</ul>
<div class="imgPreview">
<img src="" alt="" />
</div>
Try this simple demo
<!DOCTYPE html>
<html>
<head>
<script src = "jquery-1.10.2.min.js"></script>
</head>
<body>
Click to show image
<img id="image" style="display:none;height:500px; width:500px;">
<script type="text/javascript">
$('#imageLink').click(function (e){
e.stopPropagation();
$('#image').show();
});
$('body').click(function () {
$('#image').hide();
})
</script>
</body>
</html>
Remove inline event handler and write for common click event ,
1) bind the click event for all a tag inside wrapper id and then show the images when link is clicked
2) bind the click event for document and hide the all images when clicking outside of link
$("#popup1,#popup2").hide();
$("#Btn7,#Btn8").click(function (e) {
e.stopPropagation();
$(this).next().show();
})
$(document).click(function () {
$("#popup1,#popup2").hide();
})
DEMO
$(document).ready(function () {
$("#linkbutton_id").click(function () {
alert("The paragraph was clicked.");
if($("#image").hide())
{
$("#image").show();
return false;
}
});
});
$(document).ready(function () {
$("#div_id").click(function(){
$("#image").hide();
});
});
Code plus output link
https://jsfiddle.net/umxrn0Lg/2/
fullscreen output link
https://jsfiddle.net/umxrn0Lg/3/embedded/result/
I am new person in Front End Development and i am facing one major problem is that i have 3 images placed on each others and now i want to move one image so the other image comes up and then it goes and third image comes up after some interval of time.
I want three images on same position in my site but only wants to see these three images one after one after some interval of time.
Please help how i can do this??
May i use marquee property or javascript???
Non-jQuery Option
If you don't want to go down the jquery route, you can try http://www.menucool.com/javascript-image-slider. The setup is just as easy, you just have to make sure that your images are in a div with id of slider and that div has the same dimensions as one of your images.
jQuery Option
The jQuery cycle plugin will help you achieve this. It requires jquery to work but it doesn't need much setting up to create a simple sliple slideshow.
Have a look at the 'super basic' demo:
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
});
It has many options if you want something a bit fancier.
Here you go PURE JavaScript solution:
EDIT I have added image rotation... Check out live example (link below)
<script>
var current = 0;
var rotator_obj = null;
var images_array = new Array();
images_array[0] = "rotator_1";
images_array[1] = "rotator_2";
images_array[2] = "rotator_3";
var rotate_them = setInterval(function(){rotating()},4000);
function rotating(){
rotator_obj = document.getElementById(images_array[current]);
if(current != 0) {
var rotator_obj_pass = document.getElementById(images_array[current-1]);
rotator_obj_pass.style.left = "-320px";
}
else {
rotator_obj.style.left = "-320px";
}
var slideit = setInterval(function(){change_position(rotator_obj)},30);
current++;
if (current == images_array.length+1) {
var rotator_obj_passed = document.getElementById(images_array[current-2]);
rotator_obj_passed.style.left = "-320px";
current = 0;
rotating();
}
}
function change_position(rotator_obj, type) {
var intleft = parseInt(rotator_obj.style.left);
if (intleft != 0) {
rotator_obj.style.left = intleft + 32 + "px";
}
else if (intleft == 0) {
clearInterval(slideit);
}
}
</script>
<style>
#rotate_outer {
position: absolute;
top: 50%;
left: 50%;
width: 320px;
height: 240px;
margin-top: -120px;
margin-left: -160px;
overflow: hidden;
}
#rotate_outer img {
position: absolute;
top: 0px;
left: 0px;
}
</style>
<html>
<head>
</head>
<body onload="rotating();">
<div id="rotate_outer">
<img src="0.jpg" id="rotator_1" style="left: -320px;" />
<img src="1.jpg" id="rotator_2" style="left: -320px;" />
<img src="2.jpg" id="rotator_3" style="left: -320px;" />
</div>
</body>
</html>
And a working example:
http://simplestudio.rs/yard/rotate/rotate.html
If you aim for good transition and effect, I suggest an image slider called "jqFancyTransitions"
<html>
<head>
<script type="text/javascript">
window.onload = function(){
window.displayImgCount = 0;
function cycleImage(){
if (displayImgCount !== 0) {
document.getElementById("img" + displayImgCount).style.display = "none";
}
displayImgCount = displayImgCount === 3 ? 1 : displayImgCount + 1;
document.getElementById("img" + displayImgCount).style.display = "block";
setTimeout(cycleImage, 1000);
}
cycleImage();
}
</script>
</head>
<body>
<img id="img1" src="./img1.png" style="display: none">
<img id="img2" src="./img2.png" style="display: none">
<img id="img3" src="./img3.png" style="display: none">
</body>
</html>
Fiddle: http://jsfiddle.net/SReject/F7haV/
arrayImageSource= ["Image1","Image2","Image3"];
setInterval(cycle, 2000);
var count = 0;
function cycle()
{
image.src = arrayImageSource[count]
count = (count === 2) ? 0 : count + 1;
}
Maybe something like this?