How to hide div by onclick using javascript? - javascript

I have used a javascript to show div by onclick but when i click outside div i want to hide the div. How to do it in javascript? i'm using javascript code..
<a href="javascript:;" onClick="toggle('one');">
function toggle(one)
{
var o=document.getElementById(one);
o.style.display=(o.style.display=='none')?'block':'none';
}

HTML
show/hide
Javascript
// click on the div
function toggle( e, id ) {
var el = document.getElementById(id);
el.style.display = ( el.style.display == 'none' ) ? 'block' : 'none';
// save it for hiding
toggle.el = el;
// stop the event right here
if ( e.stopPropagation )
e.stopPropagation();
e.cancelBubble = true;
return false;
}
// click outside the div
document.onclick = function() {
if ( toggle.el ) {
toggle.el.style.display = 'none';
}
}

you can use blur() function when you clicked somewhere else
$("#hidelink").click(function() {
$("#divtoHide").show();
});
$("#hidelink").blur(function() {
$("#divtoHide").hide();
});

Use jQuery and this will be as easy as:
$("button.hide").click(function(event){ $("div.hidethis").hide() });

Related

How to fix: Script Causing Page Refresh (return false; not working)

I have two javascript functions. The one shows and hides div's by their ID. This has been working fine until now. I have since added some code I found online that prevents iOS from opening links in a new window (when in fullscreen mode). Since adding this new code everytime I click on a div to show/hide it, the functions fires but then the page refreshes. Any help?
I have tried to put return false in every conceivable place.
I changed my onclick to 'return function();'.
I changed it to 'function();return false'.
I placed return false inside both functions.
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
<!-- The code below is in my php file -->
<a onclick="showHidden('divID')">
Clicking on the link fires the showHidden function correctly but then it also refreshes the page. I need the event listener to prevent iOS from opening links in a new window when in fullscreen mode but I also don't want the click listener to fire when I use the showHidden function, or at the least not refresh the page.
The reason it is changing pages is because you are not preventing the default action of a link click, which is in this case loading a different page. You can do this by invoking e.preventDefault() when the link is clicked.
Here is an example:
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
var links = document.querySelectorAll('a');
links.forEach(function (el) {
el.addEventListener('click', function (e) {
e.preventDefault();
var divID = this.getAttribute('hide-id');
showHidden(divID)
})
})
<a hide-id="div1">Click here</a>
<div id="div1">
This is content
</div>
<br />
<br />
<a hide-id="div2">Click here</a>
<div id="div2">
This is content
</div>
The best solution I found to this was to add a check in the eventlistener to check if the href tag was not empty:
if(curnode.href != '' )
And only after that firing the redirect:
location.href = curnode.href;

Div to toggle it's display on/off but be able to click the input

I'm trying to make it so that whenever you click on either the button OR div itself, the display toggles. But whenever I click on the input inside of the div, the div disappears.
How can this be made so that you can still click on the input and the div not disappear? I've tried setting a z-index to the input but this fails.
Appreciate any help, thank you.
function doThis() {
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
div {
background: lightgreen;
display: flex;
}
<button onclick='doThis()'>click me</button>
<div onclick='doThis()'>
text <input type="text">
</div>
If you want the input click not to trigger the div click, you can use event.stopPropagation() function. It prevents event bubbling (passing the event to higher level DOM-elements).
function doThis() {
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
div {
background: lightgreen;
display: flex;
}
<button onclick='doThis()'>click me</button>
<div onclick='doThis()'>
text <input onclick='event.stopPropagation()' type="text">
</div>
For a pure JavaScript solution (that doesn't need jQuery), see this answer from #Sabaz to How do I prevent a parent's onclick event from firing when a child anchor is clicked?:
document.getElementById("clickable").addEventListener("click", function( e ){
e = window.event || e;
if(this === e.target) {
// put your code here
}
});
Your code wont be executed if clicked on parent's childs
you can do this:
function doThis(evt) { // <-- new: add argument
evt.preventPropagation() // <-- new, works in all new browsers
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
And add to your html:
onclick='doThis(event)'
Why cant you implement event stopPropagation for all input objects, Try ..
// select elements with js selectors and bind it
document.querySelector('input').onclick = function(e){
e.stopPropagation()
};
and here is answer by Rex M
Just check the target element which is clicked
function doThis() {
if(event.target.nodeName != "INPUT"){
var el = document.querySelector('div');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
}

Onclick function that changes the css of a element

I now have this onclick function:
<p onclick="open3()" >Uw tuin blijft mooi door vakkundig en regelmatig onderhoud.</p>
function open3 ()
{
document.getElementById("c").style.display = "block";
}
What I want is that when I clicked on open three that it somehow changes it's value so I can click on it again to set style.display to none.
I tried this with a Boolean that set's it to true or false and then changes that but that didn't work
You can add an if statement that checks the current value of the applied style and changes it appropriately.
Using this approach you don't need to declare (and keep) any additional variable in your code, while still being able to achieve the desired effect.
An example is shown below.
function open3 () {
var c = document.getElementById('c');
if (c.style.display === 'block') {
c.style.display = 'none';
} else {
c.style.display = 'block';
}
}
Try using a check in the function:
function open3 () {
var c = document.getElementById("c");
if (c.style.display === 'block') {
c.style.display = 'none';
} else {
c.style.display = 'block';
}
}
Using pure Javascript:
function open3 ()
{
if (document.getElementById("c").style.display == "block")
document.getElementById("c").style.display = "none";
else
document.getElementById("c").style.display = "block";
}
Or you can use jQuery instead:
function opne3()
{
$("#c").toggle();
}
Hope it helps.
My approach is slightly different and creates a toggler function that returns a function to toggle whatever elements you pass into it with an initial state. You can keep reusing this function whenever you need to toggle an element so you don't repeat code.
var toggler = function(el, init) {
var flag = init;
return function(e) {
flag = !flag;
el.style.display = flag ? 'block' : 'none';
};
}
Create a new function passing in the element to be toggled and its initial state.
var toggleC = toggler(document.querySelector('#c'), false);
Remove the inline JS (best practice) and use addEventListener to target the element instead.
document.querySelector('#clicker').addEventListener('click', toggleC);
DEMO
A short version of the if/else answers on this page:
function open3 () {
var c = document.getElementById('c');
c.style.display = (c.style.display == 'block' ? 'none': 'block');
}
Try this
HTML:
<p id="togglethingy">Uw tuin blijft mooi door vakkundig en regelmatig onderhoud.
CSS:
#togglethingy{
display:block;
}
jQuery:
$(function(){
var $tog_ele = $("#togglethingy")
$tog_ele.click(function() {
$tog_ele.toggle();
});
});

Use the same keypress to show a div and hide another, repeatedly, using Javascript

Lets call the 2 divs in question div1 and div2.
What I'm trying to do is use the enter key to show div1 and hide div2 (if div2 is currently visible) and vice-versa. Right now I have the code so that pressing enter will show div1 and hide div2, but to go back to having div2 shown and div1 hidden you have to use the shift key. The way it is now works, but I would like it so I only have to press enter each time I want the divs to alternate.
Here is the javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var keys = [];
var code = [13];
var keys1=[];
var code1 = [16];
$(document).keydown(function(keyEvent) {
keys.push(keyEvent.keyCode);
keys1.push(keyEvent.keyCode);
if ( keys.length > code.length ) {
keys.shift();
}
if ( keys1.length > code1.length ) {
keys1.shift();
}
if ( keys.toString() == code.toString() ) {
showAns();
}
if ( keys1.toString() == code1.toString() ) {
hideAns();
}
});
});
</script>
Any idea how to accomplish what I'm asking?
Try this sample of what you want to achieve:
var toShow = true;
$(document).keydown(function(keyEvent) {
if(keyEvent.keyCode == 13){
$('#div1').toggle(toShow);
$('#div2').toggle(!toShow);
toShow = !toShow;
}
});
I'll give you a nudge in the right direction, but won't supply you the answer outright.
You need to find a way to check the property of your elements visibility ( How do I check if an element is hidden in jQuery? This might help you!), and add that to your conidtion like so:
if(KeyIsPressed && element.IsVisible)
{
HideElement
}
else if(KeyisPressed)
{
ShowElement
}
Without getting too fancy, you can use a 'state' variable to hold that information, and then synchronize that to the DOM:
var state = {
"div1": true,
"div2": false,
};
synchronizeState();
$(document).on("keydown", function(event) {
if(event.which === 13) {
state.div1 = !state.div1;
state.div2 = !state.div2;
synchronizeState();
}
});
function synchronizeState() {
if(state.div1) {
$("#div1").show();
} else {
$("#div1").hide();
}
if(state.div2) {
$("#div2").show();
} else {
$("#div2").hide();
}
}
Working example: http://jsbin.com/eJiPavO/1/

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources