Javascript - Onclick show inline - hide if clicked somewhere else - javascript

I want a text to be shown, when a button is clicked, and hidden again when you click somewhere else.
I added an onclick function, that changes the display from none to inline and vice versa.
What do I have to change, to make the text disapear again, without having to click the button again?
Thanks for your help!
EDIT:
Solved it with the "onBlur" event, setting it to hide again.

Remove your current click handler. Then instead add one to the document and check e.target if it's your button or not.
var toggle = document.getElementById('toggle');
document.addEventListener('click', function(e) {
toggle.style.display = e.target.id === 'btn' ? 'block' : 'none';
}, false);
Handling for old browsers not included
http://jsbin.com/ijawig/1

Put this code between `<script></script> tags
document.onclick = onclickFunc;
function onclickFunc(e) {
if (!e) var e = window.event
var id = e.srcElement.id;
if(id != 'btnId') {
/*write your code to hide the panel*/
}
}

Related

Clickoutside event doen't work on iframe

It's a rich-text editor,there is a div show the content users typed in, just like this:
<div class=‘content’>
<iframe data-role=text-editable.></iframe>
</div>
When i click a icon who's used to call the color panel,the panel will show.And i wish when i click outside the panel,it will be hide.so my code is:
var color_panel = $('.color-panel');
color_panel.on("clickoutside", function (e) {
var t = $(e.target);
if ($.contains(color_panel[0], t[0]))
return;
color_panel.hide();
})
It works well when i click outside the panel will disappear except i click the iframe.when i click the ifame,nothing happens,the panel is still shown,
Help......i want to know the reason .please...is the ifame not the dom element outside the panel?
You can listen for outside clicks by listening for clicks on the body element of the webpage (so, clicking on anything element) and then you can exclude your .color_panel from this event by making another event that says "when I get clicked on, ignore any other clicks". The effect will be exactly what you want, that you can listen for outside clicks:
var panelOpen = false;
$('body').click(function(event) {
if (panelOpen) {
panelOpen = false;
color_panel.hide();
}
});
$('.color_panel').click(function(event) {
panelOpen = true;
//callYourMethodToShowThePanelHere();
e.preventDefault(); // these methods will stop the body click event
e.stopPropagation();
return false;
});

.click() event not working for mobile in Javascript

I am having a problem with my code, I have a hidden a href link that the href value is added once a click is detected in a image and the link is pass as a value the the hidden href. So once it clicks on the image in Javascript I am making the manually .click() to the hidden href tag but it is not working in mobiles. My code is below:
processGridClick : function(obj){
var objIndex = obj.getAttribute('data-item-number');
var docType = obj.getAttribute('data-doc-type');
if(obj.className.indexOf('single') > -1){
var documentURL = "";
var documentsJsonRoot = DocumentsMgr.documentationData.documents[objIndex];
if(docType == 'reportsList'){
documentURL = documentsJsonRoot.reportsList[0].url;
}else if(docType == 'attachmentList'){
documentURL = documentsJsonRoot.attachmentList[0].url;
}
dojo.attr('linkDocumentsSingle', "href", documentURL);
document.getElementById('linkDocumentsSingle').click();
}
}
The view is a table that is generated in base of a JSON object and it can have more than one row, the value of the href is passed in base of the image that they clicked. This works good for desktop but in mobile the .click is not working, I even tried to add manually the touchstart event to all the clickable elements with the code below but stills not working.
**(function(window){
// check for touch
if (Modernizr.touch) {
// run the forEach on each figure element
[].slice.call(document.querySelectorAll("figure")).forEach(function(el,i){
// check if the user moves a finger
var fingerMove = false;
el.addEventListener("touchmove",function(e){
e.stopPropagation();
fingerMove = true;
});
// always reset fingerMove to false on touch start
el.addEventListener("touchstart",function(e){
e.stopPropagation();
fingerMove = false;
});
// add hover class if figure touchend and fingerMove is false
el.addEventListener("touchend",function(e){
e.stopPropagation();
if (fingerMove == false) {
classie.toggle(el,"hover");
}
});
});
}
})(window);**
Will this work for mobile? Try simulating a mouse click...?
var ele = document.getElementById('linkDocumentsSingle');
ele.dispatchEvent(new MouseEvent('mousedown'));
ele.dispatchEvent(new MouseEvent('mouseup'));
Try to use this
In i phones there is a click event only for anchor tag or buttons. So for image, div or span you have to use tap event.
// listen for a touchstart event
$('img').on('touchstart.tap',function (e) {
// listen for a touchend event
$(e.target).one('touchend.tap',function() {
$(e.target).trigger('tap');
});
// cancel it in 150ms
setTimeout(function () {
$(e.target).off('touchend.tap');
},150);
});
This will trigger a tap event if a touchend follows a touchstart within 150ms (which you can adjust, of course). You could try using this in lieu of including jQuery mobile if a tap event is all you're after.
Note: For this i have examined you have included bootstrap js library

Hide div when user clicks outside unless closing lightbox

I'm currently using the following code to allow a user to show/hide a div on click.
When clicking anywhere outside of the div, it closes the div.
However, there is a link within the div which can open a lightbox. When a user goes to close that lightbox, it also closes the div that the link was contained. Is there anything I can add into the script to stop that from happening?
$(document).ready(function(){
$("a.dropdown-link").click(function(evt) {
evt.preventDefault();
var $div = $(this).next('.info-container');
$(".info-container").not($div).slideUp();
if ($div.is(":visible")) {
$div.slideUp()
} else {
$div.slideDown();
}
});
$(document).click(function(e){
var p = $(e.target).closest('.dropdown').length
if (!p) {
$(".info-container").slideUp();
}
});
$('.movie-link').magnificPopup({type:'iframe'});
});
<a class="dropdown-link" href="#"><div class="dropdown dropdown-processed">More info</div></a>
<div class="info-container" style="display: none;">Video preview: <a class="movie-link" href="videourl"></a></div>
I'm using Magnific Popup for the lightbox: http://dimsemenov.com/plugins/magnific-popup/
My JavaScript knowledge is pretty basic so any help is appreciated.
In the "click to close div function, you can check if the lightbox is on or not. A simple if ($("#lightbox").css("display") == "none") should be able to do the trick
EDIT: put this line after the $(document).ready line
var state = 0; // default state
$('.movie-link').click(function() { state = 1; }); // state = 1, lightbox on
in the source code, on line 384, insert this code
state = 2; //state = 2, lightbox close button clicked
the idea is not firing the "close div" function when the state is 1 (lightbox is on and clicking random stuffs inside, or outside the lightbox) or 2 (lightbox's close button got clicked), and return state to 0 when it was 2
so instead of the if I provided in the comment use this
if (state == 2) {
state = 0;
} else if (state == 0) {
//rest of the code
}
this is just something I put together and haven't tested yet, so I don't actually know if it works or not so just back up your js files just in case.
EDIT 2:
remove all the changes in edit 1 and use this on instead of the if (state == 2) {
if (e.target != $('.mfp-bg')[0] and e.target != $('.mfp-wrap')[0]) {
EDIT 3
var e_class = $(e.target).attr('class');
if (e_class != 'mfp-close' && e_class != 'mfp-container') {
working example: http://imgcrash.comeze.com/test.html
I'm not 100% without actually testing this out but you may be running into issues with $(document).click(...); since clicking anywhere on the document would trigger this event.
When you close the popup you're probably triggering this event and sliding up the info-container div.
It seems that you're looking for clicks on the divs with the class .dropdown. Why not use something like:
$('.dropdown').click(function(e) { ... });
Try this:
$("a.dropdown-link").click(function(evt) {
evt.preventDefault();
evt.stopPropagation(); //We stop the propagation of the event
//Changed it to slideToggle and added stop to prevent weird animation
//on multiple clicks
$(this).next('.info-container').stop().slideToggle()
});
$(document).click(function(e){
//Check if it has the class info-container
if (!$(e.target).hasClass("info-container")) {
$(".info-container").slideUp();
}
});
$('.movie-link').magnificPopup({type:'iframe'});
Fiddle

Stop element from disappearing when clicked

I'm writing a simple jQuery plugin that will dynamically place a div under a text box whenever it has focus. I've been able to get the position just about right in all the browsers.
I have to attach two event handlers as well on the focus and blur events of the textbox. And it works okay, but the problem is that the div that has been placed under the textbox closes even when we click on it. Now it makes sense why it would so happen, it's because the textbox loses focus, but is there a way I can stop it from happening?
I tried attaching this to the blur event handler -
if($(mainElem).is(":focus")) return;
where mainElem is the div that is shown below the textbox.
Here is a jsFiddle to illustrate the problem.
You are not going to be able to use the blur event if you want to place "clickable" elements in the div that shows. One way to solve this is to bind your event listener to a more global element like the document and then filter out the targets.
Here is a code sample:
$(document).on('click', function (e) {
var targetEl = e.target,
parent = $(e.target).parents()[0];
if (relElem[0] === targetEl || self[0] === targetEl || self[0] === parent) {
$(mainElem).show();
} else {
$(mainElem).hide();
}
});
Here is an update to your fiddle: http://jsfiddle.net/9YHKW/6/
This is a fiddle that I threw together for a project a while back: http://jsfiddle.net/MYcZx/4/
While it is not based off of your fiddle (and I do apologize) I believe that the functionality is much the same as what you're looking for. My example does not include input fields, but rather spans that hold the values. And while I'm not managing focus/blur, you could add a tabIndex attribute to the spans and then add a trigger on focus that would open the menu.
var $sub = $('.subscription');
$sub
.on('click', '.remove', function() {
$(this).parent().remove();
})
.on('click', 'li', function(e) {
var $this = $(this),
$parent = $this.parent(),
$options = $parent.children('li'),
$value = $parent.siblings('.value'),
isMulti = $parent.hasClass('multi'),
values = [];
if(!isMulti) {
$options.removeClass('active');
}
$this.toggleClass('active');
$options.filter('.active').each(function() {
values.push($(this).text());
});
$value.text(values.join(', ') || 'select');
$value[(values.length ? 'add' : 'remove') + 'Class']('set');
});
var $clone = $sub.clone(true);
$('.new')
.on('click', function() {
$(this).before($clone.clone(true));
});

How to trigger focusout event on a ul element?

I have a plugin that changes the look of select html tag on all browser.
I'm trying to make the new styled set of elements behave like a normal select tag. I'm almost there, but I only need to figure one thing out and that's how to hide a ul on focus out.
First off, here is a demo of the new select element (not in English, but you can find it easily ^^) :
http://mahersalam.co.cc/projects/n-beta/
If you click the toggle button of the select element, and then click away, the ul element that has the options won't disappear. That's because I can't fire a focusout event on that ul.
Here is the code that controls how the events are handled:
// Make a div which will be used offline and then inserted to the DOM
$namodgSelect = $('<div class="namodg-select"></div>');
/* other stuff ... */
$namodgSelect // Handle all needed events from the wrapper
.delegate('a', 'click focus blur', function(e) {
// Type of the event
var type = e.type,
// Declare other vars
id,
$this;
e.preventDefault(); // Stop default action
// Make an id ot the element using it's tag name and it's class name
// Note: Because we add a class on the active toggler, it's easier to remove it from here and the logic will still work
id = e.target.tagName.toLowerCase() + '.' + e.target.className.replace(' toggler-active', '');
switch (id) {
case 'p.selected': case 'div.toggle-button':
// Only accept 'click' on p and div
if ( type != 'click') {
return;
}
// Show and hide the options holder
if ( $optionsHolder.data('hidden') ) {
$selectElem.focus();
// This needs to run fast to give feedback to the user
$toggler.addClass('toggler-active').data('active', true);
// Show the options div
$optionsHolder.stop(true, true).slideDown('fast', function() {
// Sometimes fast clicking makes the toggler deavtive, so show it in that case
if ( ! $toggler.data('active') ) {
$toggler.addClass('toggler-active').data('active', true);
}
}).data('hidden', false);
} else {
$selectElem.blur();
// Hide the options div
$optionsHolder.stop(true, true).slideUp(function() {
// Only hide the toggler if it's active
if ( $toggler.data('active') ) {
$toggler.removeClass('toggler-active').data('active', false);
}
}).data('hidden', true);
}
break;
case 'a.toggler':
switch (type) {
case 'focusin':
$selectElem.focus();
break;
case 'focusout':
// Only blur when the options div is deactive
if ( $optionsHolder.data('hidden') ) {
$selectElem.blur();
}
break;
case 'click':
$selectedHolder.click();
$selectElem.focus();
}
break;
case 'a.option':
// Stop accept click events
if ( type != 'click') {
return;
}
// cache this element
$this = $(this);
// Change the value of the selected option and trigger a change event
$selectedOption.val( $this.data('value') ).change();
// Change the text of the fake select and trigger a click on it
$selectedHolder.text( $this.text() ).click();
break;
}
})
The whole code can be seen from the demo. As you can see, I already use the focusout event on the toggler and the options, so I can't hide the ul when that happens (that will disable the tab functionality).
If anyone can help me with this , it will be appreciated. Thanks.
Try out the jQuery outside events plugin
Will let you do something like:
$(this).bind( "clickoutside", function(event){
$(this).hide();
});
I was able to hide the options panel using this code:
$(document).click(function() {
if ( $optionsHolder.data('hidden') || $optionsHolder.is(':animated') ) {
return;
}
$selectedHolder.click();
})
This works because focusing on another input is like a click on the document.

Categories