show image on link click and hide it when clicked outside - javascript

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/

Related

jQuery trigger() stopPropagation() not working - bubbling occurring?

I'm working on a site that has buttons that are generated dynamically.
I'm using jQuery to toggle classes of hidden elements $('.toggle-button').on('click') (i.e. off-canvas cart, sidebar, etc.) based on data attributes
I'm using trigger('click') for the dynamic buttons and passing data through to trigger the correct hidden element. The problem is trigger() is bubbling to other buttons that have class toggle-button or that's what I think the problem is...
I've tried event.stopPropagation() but it doesn't seem to be working.
Here's a simplified version of the code I'm working with.
jQuery(document).ready(function($){
$('.toggle-button').on('click', function(event, triggerData){
console.log('toggle button triggered');
toggleClass = '';
targetSelector = '';
targetElement = '';
if ( !triggerData ) {
toggleClass = $(this).attr('data-toggle');
targetSelector = $(this).attr('data-target');
} else {
toggleClass = triggerData.toggleClass;
targetSelector = triggerData.targetSelector;
}
targetElement = $(targetSelector);
targetElement.toggleClass(toggleClass);
});
$(document).on('click', '.view-cart', function(event){
event.preventDefault();
console.log('view cart button clicked');
$('.toggle-button').trigger('click', {
toggleClass : 'show',
targetSelector : '.cart'
});
});
});
jQuery(document).ready(function($) {
$('.toggle-button').on('click', function(event, triggerData) {
console.log('toggle button triggered');
toggleClass = '';
targetSelector = '';
targetElement = '';
if (!triggerData) {
toggleClass = $(this).attr('data-toggle');
targetSelector = $(this).attr('data-target');
} else {
toggleClass = triggerData.toggleClass;
targetSelector = triggerData.targetSelector;
}
targetElement = $(targetSelector);
targetElement.toggleClass(toggleClass);
});
$(document).on('click', '.view-cart', function(event) {
event.preventDefault();
console.log('view cart button clicked');
$('.toggle-button').trigger('click', {
toggleClass: 'show',
targetSelector: '.cart'
});
});
});
.cart,
.info {
display: block;
padding: 30px;
width: 200px;
border: 1px solid #000;
visibility: hidden;
}
.cart.show,
.info.show {
visibility: visible;
}
.product {
display: inline-block;
width: 150px;
margin: 15px;
background: #e3e3e3;
text-align: center;
}
.product a {
display: block;
padding: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<button class="toggle-button" data-toggle="show" data-target=".cart">View Cart</button>
<button class="toggle-button" data-toggle="show" data-target=".info">View Info</button>
<hr>
<div class="product">
<img src="https://via.placeholder.com/150">
View Cart
</div>
<div class="product">
<img src="https://via.placeholder.com/150">
View Cart
</div>
<div class="product">
<img src="https://via.placeholder.com/150">
View Cart
</div>
<div class="product">
<img src="https://via.placeholder.com/150">
View Cart
</div>
<div class="cart">
<span>This is your cart</span>
</div>
<div class="info">
<span>This is additional info</span>
</div>
</body>
</html>
there are two button with class toggle-button ...whose click event is being triggered correctly - while the problem is, that probably only one of them should be triggered. either select the element to click by a combined class attribute or by id attribute. those events are not bubbling at all, the selector just matches two elements - and that's why it subsequently clicks onto two elements.
Your code has two .toggle-button element, so $('.toggle-button').trigger() is running two times.
I recommend to name different class names of these basically.
But there is a other way not to do so, you can use :first selector as shown below.
https://api.jquery.com/first-selector/
jQuery(document).ready(function($){
$('.toggle-button').on('click', function(event, triggerData){
console.log('toggle button triggered');
toggleClass = '';
targetSelector = '';
targetElement = '';
if ( !triggerData ) {
toggleClass = $(this).attr('data-toggle');
targetSelector = $(this).attr('data-target');
} else {
toggleClass = triggerData.toggleClass;
targetSelector = triggerData.targetSelector;
}
targetElement = $(targetSelector);
targetElement.toggleClass(toggleClass);
});
$(document).on('click', '.view-cart', function(event){
event.preventDefault();
console.log('view cart button clicked');
$('.toggle-button:first').trigger('click', {
toggleClass : 'show',
targetSelector : '.cart'
});
});
});

JS: Hovered images don't load smoothly

I'm using JS to change pictures on hover... but the hovered pictures don't load smoothly. Any help is appreciated.
<script type="text/javascript">
$( document ).ready(function() {
$('.img-grey').on({
mouseenter: function (e) {
var greysrc = $(this).attr('src');
var colorsrc = greysrc.replace("1.jpg", "2.jpg")
$(this).attr('src', colorsrc);
},
mouseleave: function (e) {
var colorsrc = $(this).attr('src');
var greysrc = colorsrc.replace("2.jpg", "1.jpg")
$(this).attr('src', greysrc);
}
})
});
</script>
Alternatively this task can be solved with css. Check the css attribute selectors https://www.w3schools.com/css/css_attribute_selectors.asp
All you need is to create next html structure:
<div class="container">
<img src="1path-to-1.jpg" />
<img src="1path-to-2.jpg" />
</div>
<div class="container">
<img src="2path-to-1.jpg" />
<img src="2path-to-2.jpg" />
</div>
See attached snippet
.container [src$="2.jpg"] {
display: none;
}
.container:hover [src$="1.jpg"] {
display: none;
}
.container:hover [src$="2.jpg"] {
display: inline;
}
.container {
float: left;
}
<div class="container">
<img src="https://www.gravatar.com/avatar/8aecf6164a04433529bd7702f1b5f59a?s=128&d=identicon&r=PG&f=1&1.jpg" />
<img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>
<div class="container">
<img src="https://www.gravatar.com/avatar/b8367b2f25ceee4d54595495b4e51312?s=128&d=identicon&r=PG&f=1&1.jpg" />
<img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>
<div class="container">
<img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&1.jpg" />
<img src="https://www.gravatar.com/avatar/8aecf6164a04433529bd7702f1b5f59a?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>
If you want to preload your images you should put them into DOM or add as background properties. Here's modified version of your code that adds hidden <img /> elements next to existing. I haven't run it, but it should works
$( document ).ready(function() {
$('.img-grey').map(function () {
var temp = document.createElement('img');
temp.src = this.src.replace("1.jpg", "2.jpg");
temp.style.display = 'none';
$(this).parent().append(temp);
return this;
}).on({
mouseenter: function (e) {
var greysrc = $(this).attr('src');
var colorsrc = greysrc.replace("1.jpg", "2.jpg")
$(this).attr('src', colorsrc);
},
mouseleave: function (e) {
var colorsrc = $(this).attr('src');
var greysrc = colorsrc.replace("2.jpg", "1.jpg")
$(this).attr('src', greysrc);
}
})
});

Hide pop-up by clicking outside it (problems with Philip Waltons solution)

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>

How to show a indicator when clicked on a Button in this case

On Click Of the Try Again Button , is it possible to show some processing happening on the device
My jsfiddle
My code as below
$(document).on("click", ".getStarted", function(event) {
// Simulating Net Connection here
var a = 10;
if (a == 10) {
$('#mainlabel').delay(100).fadeIn(300);
$('#nonetconnmain').popup({
history : false
}).popup('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
});
$(document).on('click', '.nonetconnmainclose', function(event) {
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
$(document).on("popupbeforeposition", "#nonetconnmain", function(event, ui) {
$('#mainlabel').hide();
});
With my code , the functionality is working , but it seems that the application is not doing any action
So my question is it possible to show any indication (For example , delay , progressbar , anything )
Here ya go
$(document).on("click", ".getStarted", function(event) {
$.mobile.loading("show", {
text: "",
textVisible: true,
theme: "z",
html: ""
});
// Simulating Net Connection here
var a = 10;
if (a == 10) {
setTimeout(function() {
$.mobile.loading("hide");
$('#mainlabel').fadeIn(300);
}, 1000);
$('#nonetconnmain').popup({
history: false
}).popup('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
});
$(document).on('click', '.nonetconnmainclose', function(event) {
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
$(document).on("popupbeforeposition", "#nonetconnmain", function(event, ui) {
$('#mainlabel').hide();
});
.popup {
height: 200px;
width: 150px;
}
.popup h6 {
font-size: 1.5em !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<link href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" rel="stylesheet" />
<div data-role="page">
<div data-role="popup" id="nonetconnmain" data-dismissible="false" class="ui-content" data-theme="a">
<div class="popup_inner popup_sm">
<div class="popup_content" style="text-align:center;">
<p class="">Please check net connectivcty</p>
<label id="mainlabel" style="margin:100px auto 60px auto;color:Red; line-height:40px;font-size:medium;display:none">Please check</label>
</div>
<div class="popup_footer nonetconnmainclose">
<a class="">Try Again</a>
</div>
</div>
</div>
<button class="getStarted btn btn-a get_btn">Click Here</button>
</div>
You can use a small function (with time as parameter) and use jQuery animate() to create the process effect like below.
var updateProgress = function(t) {
$( "#p" ).css("width",0);
$( "#p" ).show();
$( "#p" ).animate({ "width": "100%" }, t , "linear", function() {
$(this).hide();
});
}
Do notice that the time that is chosen when calling updateProgress() is relevant with the delay and the fade in effect of the text message
updateProgress(3500);
$('#mainlabel').delay(3400).fadeIn(600);
Check it on the snippet below
var updateProgress = function(t) {
$( "#p" ).css("width",0);
$( "#p" ).show();
$( "#p" ).animate({ "width": "100%" }, t , "linear", function() {
$(this).hide();
});
}
$(document).on("click", ".getStarted", function(event) {
var a = 10;
if(a==10)
{
updateProgress(3500);
$('#mainlabel').delay(3400).fadeIn(600);
$('#nonetconnmain').popup({history: false}).popup('open');
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
});
$(document).on('click', '.nonetconnmainclose', function(event) {
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
$(document).on("popupbeforeposition", "#nonetconnmain",function( event, ui ) {
$('#mainlabel').hide();
});
.popup {
height: 200px;
width: 400px;
}
.popup h6 {
font-size: 1.5em !important;
}
#p {
border:none;
height:1em;
background: #0063a6;
width:0%;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<link href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" rel="stylesheet"/>
<div data-role="page">
<div data-role="popup" id="nonetconnmain" data-dismissible="false" class="ui-content" data-theme="a">
<div class="popup_inner popup_sm">
<div class="popup_content" style="text-align:center;">
<p class="">Please check net connectivcty</p>
<div id="p"></div><br>
<label id="mainlabel" style="margin:100px auto 60px auto;color:Red; line-height:40px;font-size:medium;display:none">Please check </label>
</div>
<div class="popup_footer nonetconnmainclose">
<a class="">Try Again</a>
</div>
</div>
</div>
<button class="getStarted btn btn-a get_btn">Click Here</button>
</div>
Fiddle
Probably when you click on try again , you can have a setinterval triggered which can check for online connectivity and when found can close the popup and get started again, also when we do retries in the interval the progress can be shown as progressing dots..
Below is the code, i haven't tried to run the code, but it shows the idea
$(document).on('click', '.nonetconnmainclose', function(event) {
var msgUI = $("#mainlabel");
msgUI.data("previoustext",msgUI.html()).html("retrying...");
var progress = [];
var counter = 0 ,timeout = 5;
var clearIt = setInterval(function(){
var online = navigator.onLine;
progress.push(".");
if(counter > timeout && !online){
msgUI.html(msgUI.data("previoustext"));
counter=0;
}
if(online){
$('#nonetconnmain').popup('close');
$(".getStarted").trigger("click");
counter=0;
clearInterval(clearIt);
}
else{
msgUI.html("retrying" + progress.join(""));
counter++;
}
},1000);
event.stopImmediatePropagation();
event.preventDefault();
return false;
});
Sure,
try appending a loader GIF to one of the div and remember to remove the same when your process is finished.
Kindly refer to StackOverflow
And try appending this
$('#nonetconnmain').append('<center><img style="height: 50px; position:relative; top:100px;" src="cdnjs.cloudflare.com/ajax/libs/semantic-ui/0.16.1/images/…; alt="loading..."></center>');
This will append a loader to your HTML to show some kind of processing.

swap div's position from top div's

I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML
<div class="wrap top">
<input type="text" value="div1" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div3" class="textbox " />
</div>
jQuery
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(this).insertBefore($(this).prev());
}
});
}(jQuery));
The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?
I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(".wrap").removeClass("top");
$(this).addClass("top");
}
});
}(jQuery));
this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
var $this = $(this);
if ($this.index() == 0) {
} else {
var first = $this.siblings('.wrap').first();
first.insertBefore($this);
$this.prependTo($this.parent());
}
});
if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());
To swap the two DOM elements using jQuery, you could use something like this: -
(function($) {
$(".wrap").on("click", function(event) {
var index = $(event.target).index();
var first = $(".wrap").first();
if (index > 0) {
$(first).swapWith(this);
}
});
}(jQuery));
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
.wrap {
height: 100px;
width: 200px;
margin: 10px 10px 10px 10px;
background-color: #2d8cd0;
}
h2 {
color: white;
text-align: center;
padding-top: 20px;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrap">
<h2>1</h2>
</div>
<div class="wrap">
<h2>2</h2>
</div>
<div class="wrap">
<h2>3</h2>
</div>
<div class="wrap">
<h2>4</h2>
</div>

Categories

Resources