This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 8 years ago.
Im using a very simple and clean code to render a modal in my page:
<div class="modal">I'm the Modal Window!</div>
.modal {
/* some styles to position the modal at the center of the page */
position: fixed;
top: 50%;
left: 50%;
width: 300px;
line-height: 200px;
height: 200px;
margin-left: -150px;
margin-top: -100px;
background-color: #f1c40f;
text-align: center;
/* needed styles for the overlay */
z-index: 10; /* keep on top of other elements on the page */
outline: 9999px solid rgba(0,0,0,0.5);
}
http://jsfiddle.net/c89Ls0av/
Is there a clean and reliable way to detect when somebody clicks outside of the modal?
Probably the simplest way is to bind click event to body and see if it comes from the element (e.target) which has parent (walk up the tree with closest method) .modal:
$(document).click(function(e) {
if (!$(e.target).closest('.modal').length) {
alert('click outside!');
}
});
Demo: http://jsfiddle.net/c89Ls0av/4/
By the way, overlay made with outline is an interesting idea, but it's not real overlay, as it still allows to interact with underlying page elements. Here is an example of the overlay made with div container covering entire page: http://jsfiddle.net/c89Ls0av/5/. This one will prevent page interaction when modal is visible.
And here is an example of how open/close functionality can be use together: http://jsfiddle.net/c89Ls0av/7/.
WithOut jQuery
document.addEventListener('click', function (e) {
if(e.target.className === 'modal'){
alert('clicked in');
}else {
alert('clicked out');
}
}, false);
check it out:
http://jsbin.com/totonopili/1/edit?html,css,js,output
With the help of a javascript framework this is quite easy.
Follow these steps:
Attach a click event to the document which closes or hides the modal.
Attach a separate click event to the window which stops click propagation.
Example:
$('html').click(function(){
$('.modal').hide();
});
$('.modal').click(function(e){
e.stopPropagation();
});
http://jsfiddle.net/c89Ls0av/3/
Warning! Stopping propagation can introduce strange behaviour
Dfsq answer will work fine.. but if you want something to do with dialog boxes you may have a look at jQuery ui dialog boxes. It gives you many options with dialog boxes which you can configure as per your needs.
http://jqueryui.com/dialog/
Related
This question already has answers here:
How to detect DIV's dimension changed?
(28 answers)
Closed 7 years ago.
UPDATE: since everyone is hung up on window resize
I've got a div inside a resizable div and I want to detect the resize of the child div. I know .on('resize') is only for the window. My question is solely based on the child div resize.
<div id='main_wrapper'>
<div id = 'child_div'>
</div>
</div>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#main_wrapper {
height: 300px;
width: 300px;
background-color: blue;
}
#child_div{
height: 100%;
width: 100%;
}
$('#main_wrapper').resizable();
$('#child_div').on('resize', function() { //i know this isn't proper, how to do this is my question.
alert('i changed');
})
https://jsfiddle.net/cyclingpaper/2kksqoLs/
Thanks for your time.
The resize event is only targetted by the window object. You can't attach it to another DOM tree element than the most top.
https://developer.mozilla.org/en-US/docs/Web/Events/resize
Here you go:
https://jsfiddle.net/danhaswings/ejoxphov/2/
You can't bind the resize event to anything other than the window.
// cache objects
var $main_wrapper = $('#main_wrapper');
// on window resize
$(window).resize(function() {
console.log('The window has resized.');
// random example to run on window resize
$main_wrapper.css({
'background-color': 'red'
});
});
Post Edited: Downvoters please remove the downvotes for no reason / anger!
The resize event is for window only, not for elements. Use this code instead:
$(window).on('resize', function(){
alert('i changed');
});
Fiddle: https://jsfiddle.net/effsmpdm/
Take a look at this
http://benalman.com/code/projects/jquery-resize/examples/resize/
It has various examples. Try resizing your window and see how elements
inside container elements adjusted.
Example with js fiddle to explain how to get it work. Take a look at this fiddle
http://jsfiddle.net/sgsqJ/4/
In that resize() event is bound to an elements having class "test" and
also to the window object and in resize callback of window object
$('.test').resize() is called.
e.g.
$('#test_div').bind('resize', function(){
console.log('resized');
});
$(window).resize(function(){
$('#test_div').resize();
});
Source: How to detect DIV's dimension changed?
I have made a website, something like a control panel that controls different devices connected to microcontroller (the website itself is hosted on microcontroller).
I encounter this problem: If user change state of some check box (you can think of them like on/off buttons) and immediately after that sends some other command, my system crashes. To avoid this I need to introduce delay that would disable user for clicking any other button on website for specific amount of time (in my case 5 seconds). I am using JavaScript to communicate http requests to/and from my microcontroller so I am looking for JavaScript based solution.
Hope I made myself clear and thank you for your help.
Since the post states the website itself is hosted on a micro-controller, jQuery may be inappropriate (storage constraints) for the answer. The general theme however is still the same. When a user changes an appropriate control show a modal div with a 'please wait' or some other message.
You don't mention the browser you want to target so I'm assuming a chrome or firefox version.
CSS:
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.3);
z-index: 1001;
display: none;
}
.modal.active {
display: block;
}
HTML (Place this div somewhere in the root of body, and only once):
<div id="modal" class="modal">
<h3>Please wait...</h3>
</div>
JavaScript:
// get your elements
var element = document.getElementById("myField");
var modal = document.getElementById("modal");
// opens the modal
function openModal() {
modal.classList.add("active");
}
// closes the modal
function closeModal() {
modal.classList.remove("active");
}
// opens the modal, then closes it after a timeout period
function openTemporaryModal(var timeout) {
openModal();
setTimeout(function() {
closeModal();
}, timeout);
}
// used as an event callback
function modalForFiveSeconds() {
openTemporaryModal(5000);
}
// Attach the event callback to the element/event you want to open the modal:
element.addEventListener('change', modalForFiveSeconds);
References:
MDN: document.getElementById
MDN: element.classList
MDN: window.setTimeout
MDN: element.addEventListener
You can use below step.
Create one HTML Div
Make that div as Visible false or display:none
Set height and width for Div. make it screen.Width and screen.Height
when user click on Checkbox - set that div visible=true or display:block for 5 Seconds.
After 5 Seconds make it invisible.
First of all you will need to attached an EVENT to all of the checkboxes you have.
Something like this:
$.("input[type='checkbox']").change(disableScreen);
Create a div that would disable the screen
<div id="disablingDiv" ></div>
Then we have to create a new function called disableScreen.
function disableScreen() {
var $disablingDiv= $("#disablingDiv");
$body.addClass("disablingDiv");
window.setTimeout(function () {
$body.removeClass("disablingDiv");
}, 5000);
}
.disablingDiv
{
/* Do not display it on entry */
display: none;
/* Display it on the layer with index 1001.
Make sure this is the highest z-index value
used by layers on that page */
z-index:1001;
/* make it cover the whole screen */
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
/* make it white but fully transparent */
background-color: white;
opacity:.00;
filter: alpha(opacity=00);
}
Hiding div solution was taken from "Disable all page elements with transparent div"
It may be a simple question, but being a newbie it is hard to get it to run.
So I have this leanModal javascript class, which I want to use for a modal popup.
here is the example paragraph that has to appear once an image is clicked:
<p id="lean_overlay"> Some text to appear</p>
Following is the css that is applied to it:
#lean_overlay {
position: fixed;
z-index:100;
top: 0px;
left: 0px;
height:100%;
width:100%;
background: #000;
display: none;
}
The tutorial of leanModal class says the following:
Step 3: call the function on your modal trigger, as follows. Be sure to set the href attribute of your trigger anchor to match the id of your target element.
$("#trigger_id").leanModal();
What I want to be done is once an img is clicked, the leanModal method to be called, but I got lost in the previous tutorial, in particular which element is a modal trigger and which one is the target element. Moreover, how to call a function once an image is clicked?
any help is much appreciated.
Since you mentioned image is clicked, then you can check its target by
$('img').click(function (e) {
alert(e.target);
});
I have a div pop up window which appears on button click event. I want to disable the screen when the pop up is shown to the user and enable again when user closes the pop up by escape key or close button on div, like a regular dialog box. How can I do this by java script.
JQuery UI makes your life easier.
Have a look at jquery UI dialog
You can use jQuery dialog and use the attribute modal:true
$("#fileuploadfun").dialog({ modal: true });
If you use modal:false then you can click on background
You can create a "cover" element that covers the screen preventing input from the user, except with whatever is on top (or inside) the cover.
$('#button').click(function() { $('body').append('<div class="cover"></div>'); } );
.cover { width: 100%; height: 100%; position: fixed; top: 0; left: 0; background: rgba(0, 0, 0, 0.5); }
You then assign events to the cover so when the user clicks it or presses a specific key, the cover is hidden.
$('.cover').click(function() { $(this).hide(); });
I highly recommend using a modal plugin/script, as doing it yourself requires significant effort and is time consuming (trust me).
I’ve already spent hours looking at as many online resources and stackoverflow questions as I can find but for some reason I just can’t figure this out.
I’m attempting to use CSS and image sprites to make a link display as an image that changes once it is hovered over and once it has been clicked. I’ve played round with CSS and looked at JavaScript for far too long now and I just need some direction on how to get it working.
I’ve managed to make it change once its hovered over however what i really need to do is have the image change once it is clicked. So the begin with it displays the play button and when its clicked it displays a pause button, click it again and it displays the play button etc.
From what i can gather i will need to use JavaScript and an onclick event. However I’m not sure how this would work or how to use it with image sprites.
My CSS so far looks like this
.testclass .stratus {
background-position: -1px -1px;
width: 21px;
height: 21px;}.
.testclass .stratus:hover {background-position: -1px -29px; width: 21px; height:
21px;}.
However this only effects the play button and when it is hovered over. Now i need a way to display the pause button when the play button is clicked and vice versa.
Image sprites URL.
http://www.danceyrselfclean.com/wp-content/uploads/2012/12/sprites.png
URL of page im trying to get this to work on.
http://www.priceofmilk.co.uk/uncategorized/ddd-2
Can this be achieved using CSS and HTML or will I also need to use some JavaScript? Any assistance would be much appreciated.
I made a simple example. I use background colors and an anchor but you can easy implement this in your situation.
update
Updated the code so it uses your images.
HTML
<a class="play_pause">PLAY</a>
CSS
.play_pause {
display: block;
width: 24px;
height: 23px;
text-indent: -99999px;
background: url(http://www.danceyrselfclean.com/wp-content/uploads/2012/12/sprites.png);
cursor: pointer;
}
.playing {
background-position: -27px 0;
}
.playing:hover {
background-position: -27px -28px !important;
}
.play_pause:hover {
background-position: 0 -28px;
}
And the JS:
$(document).ready(function() {
$(".play_pause").click(function() {
$(this).toggleClass('playing');
});
});
JsFiddle example
If you only wanted to detect the first click, you could do this in pure CSS by giving the link an id and using the :target pseudoclass (e.g. a#theid:target {...})
But since you need to detect a second click, you'll need to use JS to toggle between CSS classes. The basic way is to use an event handler:
document.getElementById('theid').onclick = function(){
this.className = this.className=='play' ? 'pause' : 'play';
};
You will have to use JavaScript to accomplish the switching, there is no way to accomplish such logic with pure CSS.
The easiest way to go would be to have two classes play and pause. Through CSS you declare which part of the sprite you want to show for each of those classes. Then you attach a click-event listener to the element with JavaScript, and in the click-event callback you remove class play from the element and apply class pause instead, and vice versa.
MDN has a good article on how to attach event-listeners to an element. And this SO question discuss how you can add/remove classes on an element.
That is simple where have you read?
jQuery('.testclass .stratus').click(function{
jQuery(this).toggleClass('played');
})
css:
.played{
background-position: -1px -29px;
}
Example using .querySelectorAll and .addEventListener, with your current sprite. No jQuery is used.
var elm = document.querySelectorAll('.testclass .stratus'), i = elm.length, e;
while (e = elm[--i])
e.addEventListener('click', function () { // this fn generates the listener
var pause = false; // captured in scope, not global
return function () { // this is the actual listener
this.style.backgroundPositionX = (pause = !pause)?'-20px':'0px';
}
}(), false); // the () invokes the generator