Hiding divs when clicking outside an image [duplicate] - javascript

This question already has answers here:
Detect click outside element?
(2 answers)
Hide div when clicking outside
(3 answers)
Closed 10 years ago.
I have a webpage with several hidden divs. I have them set up so that when an image is clicked, they will display and if the image is clicked again, they hide. The problem is, I need to hide them if they're visible and any part of the page is clicked. I've searched high and low and have found some suggestions but have yet to find one that works. Can anyone help?

$(window).click(function() {
$('img').hide();
});
Very simple example

I usually bind a document.click event to listen for a click outside and then remove it when the window is closed.
// in function after your image shows up.
document.click = hideImage;
// other code to hide image when image is clicked
// in function after your image is hidden.
document.click = null;
If you're using jQuery it's easier because you can namespace your events for safe add and removal.
// in function after your image shows up.
$(document).bind('click.imagehide', hideImage);
// other code to hide image when image is clicked
// in function after your image is hidden.
$(document).unbind('click.imagehide');
This method is safer so you don't interfere with other click events bound to the document.

What you need to do is prevent event bubbling. If you are using jquery you can do:
$(document).on ('click', function () { $('div').hide (); });
$('img').on ('click', function (e) { e.stopPropagation (); });
Remeber to change the selectors to fit your needs.

Related

can't interact with jquery loaded button that uses jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
JavaScript does not fire after appending [duplicate]
(3 answers)
Closed 7 years ago.
Working on a poll/voting system where people can click to see results before voting, and then click back again to see the options once more.
The problem is when loading in the results, the button I load to show the options again won't seem to work:
The code for them is basically the same (I've put an alert to test if it was even picking up the button, it is not):
$('.results_button').click(function() {
var poll_id = $(this).data('poll-id');
$('.poll_content').load('/includes/ajax/poll_results.php', {'poll_id':poll_id});
});
$('.back_vote_button').click(function() {
window.alert("Test");
//var poll_id = $(this).data('poll-id');
//$('.poll_content').load('/includes/ajax/poll_options.php', {'poll_id':poll_id});
});
The actual code to the back_vote_button is this for example:
<button name="pollresults" class="back_vote_button" data-poll-id="1">Back to voting</button>
Is there something I am missing about interacting with jquery loaded content?
Is your button being created after the doc is loaded? If doesn't exist at the time that the document is created, the listener is not bound. You can either bind a listener event or you can change the click to listen to an already created object, for a bad example try this:
$(document).on('click', '.back_vote_button', function(){
window.alert("Test");
});
this should work but it will listen every time you click on the body and then determine what you clicked on if this were the problem.

Trigger something on iframe click [duplicate]

This question already has answers here:
Detect Click into Iframe using JavaScript
(23 answers)
Closed 7 years ago.
Got a js that appends an iframe with content from other site. I need certain action to be triggered on click within the iframe.
Obviously, i can't use elements inside iframe. I've tried following, and it didn't work.
$('.container iframe').click(function(){
alert('works!");
});
Then I tried this.
$('.container').click(function(){
alert('works!");
});
click on container works, but when click happens within iframe, it doesn't work.
Can someone point me in right direction?
Thank you!
var iframeBody = $('body', $('.container iframe')[0].contentWindow.document);
$(iframeBody).on('click', function(e) {
// your code
});

Creating javascript event listeners on unique rows created by php loop

Forgive me if I word the title wrong, I'm speculating on what my problem might be as I'm not a javascript coding expert. I have a series of divs that are generated by a php loop with unique ids created by adding the unique id contained in an auto increment column in the mysql db table that contains all the info for the row.
When the user clicks on the div this function fires off:
onclick=\"showModal('".$rowInfo['ID']."_row-id')\"
javascript code:
function showModal(ID) { /* code that shows hidden modal window */ }
This works fine, however now I need to start adding javascript buttons (in my case img tags with onclick functions) to the div with the showModal onclick function.
I added this code to the showModal(ID) function:
var downArrow = document.getElementById(ID+'_down-arrow'); // Down arrow is the button users click to show addition buttons/divs
downArrow.addEventListener('click',arrowCheck,false); // checks to see if down arrow was clicked, if so arrowCheck function runs and stops propagation.
arrowCheck function:
function arrowCheck(e) { e.stopPropagation(); }
This bit of code also works but ONLY AFTER the user has clicked the div once, the first time the div is clicked both functions fire off (ie the modal window and the extra buttons that the down arrow shows) but after the first click the addEventListener does it's job and clicking the down arrow only shows extra buttons, elsewhere brings up the modal, etc.
I'm guessing I need to create the event listener before the user clicks the div and fires off showModal(), is this correct? I'm not sure how to create a unique event listener for each down arrow image before the div is clicked, or even if I need to. Thanks for any help!
Since the event listener is being created within the modal function, you need to call the modal function before the other listener is even added.
To get your desired results, you could either directly add the onclick method to the image that the PHP code creates, or you could detect when the page is finished loading and add those listeners then. To do the latter, though, you'd need to either query for something the images all have in common, like a classname, or you'd have to keep track of the IDs used and manually add a listener for each. e.g.:
<body onload="initEventhandling()">
initEventHandling = function () {
var buttons = document.getElementsByClassName("image-button");
for (button in buttons) {
button.addEventListener('click', arrowCheck, false);
}
}
David Millar's code pointed me in the right direction. I tried to put the initEventHandling function in the onload of the body tag but I couldn't get it to work. It executed the function but I could not get the eventListeners to work. I solved it by creating an event listener using the onload for each img tag, so my code ended up like this:
<img id=\"".$appChart['ID']."_down-arrow\" onload=\"addEvent('".$appChart['ID']."')\" onclick=\"clickReviewArrow('".$appChart['ID']."')\" src='...' />
javascript:
function addEvent(ID) { var downArrow = document.getElementById(ID+'_down-arrow');
downArrow.addEventListener('click',arrowCheck,false); }
function arrowCheck(e) { e.stopPropagation(); }
David Millar may have been suggesting this, if so I'll mark his answer.

Stop click from working on inner elements [duplicate]

This question already has answers here:
How to have click event ONLY fire on parent DIV, not children?
(12 answers)
Closed 10 years ago.
I have a div that covers the screen. Within the div is another div and within that, an image get dynamically placed. When the user clicks on the outer div it closes, and that is fine. When the user clicks on the image or the inner div it closes as well, how can I stop that from happening? I only want it to close if they click on the outer div.
This is what I am using; what do I need to do to make this work?
$("#black-out").click(function(){
$(this).fadeOut("slow");
});
The HTML:
<div id="black-out"><div id="image-holder"></div></div>
Check if the clicked element is the same as the one the event was bound to :
$("#black-out").click(function(e){
if (e.target == this) $(this).fadeOut("slow");
});

Disable div using Jquery [duplicate]

This question already has answers here:
How to disable all div content
(29 answers)
Closed 9 years ago.
I have the event onClick=window.location.href = 'some url stored in div.
Div contains images as well as text.
I want to show preview using this div, but want clicking disabled on this div because it is taking to the specified location.
I tried it like this:
("#preview").disabled= true;
("#preview").disabled= 'disabled';
("#preview").children().disabled= true;
("#preview").children().disabled= 'disabled';
But none of this is working in firefox 3.6. Somebody please help to solve this problem.
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
$('#preview').unbind('click');
First, why would you use an inline event handler while using a library like jQuery. Do it the unobtrusive way and bind all event handlers with Javascript.
This actually will also help you with your problem, because then you can unbind and rebind an event handler very easily:
function myclick() {
window.location.href = 'some url';
}
// bind the click event handler
$(function() {
$('#preview').bind('click', myclick);
});
// unbind the click event handler
$('#preview').unbind('click', myclick);
That way, you can add and remove the functionality, but it won't change any visible change to the div node. You would also have to add a style or css class to let an user know that something changed.
Ref.: .bind(), .unbind()
You should be able to simply do:
// Unbind all click events for all elements
("#preview *").unbind("click");
The other thing you could do is what modals often do with the background: place a non-clickable div on top of the other content.
$("#preview div").onClick = function(){};
Try
$('#the_div_id *').unbind('click');

Categories