If div is not hidden click anywhere to hide [duplicate] - javascript

This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 9 years ago.
I am trying to make a div hidden by default and show by clicking a button. To close the div, I can either click on the button or anywhere else on the screen. Below is my attempt but the closing part is not working. I appreciated if anyone can point me to the right implementation or maybe a better way to do this.
$('#theDiv').hide();
$("#showDivBtn").click(function(){
$("#theDiv").show();
});
if ( !$('#theDiv:hidden') ) {
$(document).click(function() {
$('#theDiv').hide();
});
$('#theDiv').click(function(e) {
e.stopPropagation();
return false;
});
}
});

placing the entire event handler inside a condition only checks the condition on first pageload, and the event handler is probably never attached, try it like this instead :
$('#theDiv').hide();
$(document).on('click', function(e) {
if ( $(e.target).closest('#showDivBtn').length ) {
$("#theDiv").show();
}else if ( ! $(e.target).closest('#theDiv').length ) {
$('#theDiv').hide();
}
});
FIDDLE

Try this,
$('#theDiv').hide();
$("#showDivBtn").click(function(){
$("#theDiv").toggle();
});
$(document).on("click" , function(event){
if( $(event.target).attr("id") != "theDiv" && $(event.target).attr("id") != "showDivBtn" && $(event.target).parents("#theDiv").attr("id") != "theDiv")
{
$('#theDiv').hide();
}
});

try using
if( !$('.theDiv' ).is( ':visible' ) )
instead of
if ( !$('.theDiv:hidden') )

try this
<script type="text/javascript">
$('.opendiv').hide();
$(document).click(function (event) {
var $target = $(event.target);
if ($target.attr('id') == 'addAccordion') {
if ($('.opendiv').is(':hidden')) {
$('.opendiv').show();
}
else {
$('.opendiv').hide();
}
}
else if ($target.closest('.opendiv').length > 0) {
}
else {
$('.opendiv').hide();
}
})
</script>
<div>
<input id="addAccordion" type="button" value="ADD COMMENT" />
</div>
<div id="rs" class="opendiv">
<h2>
Welcome to ASP.NET!
</h2>
<p>
To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">
www.asp.net</a>.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
</div>

I don't think you can target document with a .click handler like that.
Rather than making it so you can literally click anywhere to close the DIV, just make it seem that way. Put a clear DIV behind the one that you want to be able to close and make it cover the whole screen. Then you can attach your click handler to that.
HTML:
<button>Click me to show the DIV</button>
<div class="container">
<div class="thediv">
<p>I'm the DIV</p>
</div>
</div>
JavaScript:
$(document).ready(function () {
var $button = $("button");
var $container = $("div.container");
$button.click(function () {
$container.show();
});
$container.click(function () {
$container.hide();
});
});
CSS:
div.container {
display: none;
position: fixed;
top: -5%;
left: -5%;
width: 110%;
height: 110%;
}
div.thediv {
position: absolute;
top: 30%;
left: 10%;
background-color: gray;
color: white;
padding-top: 1em;
border-radius: 5px;
width: 50%;
}
p {
background-color: black;
text-align: center;
padding: 2em;
}
For demonstration purposes, I made the background DIV visible in this Fiddle

Related

How can I prevent my blur event form over ridding my click event?

I have a menu which I want to display when the input is focused, so I used the focus and blur event of the input to trigger the function that either shows or hide the menu.
The problem is when I want to add events inside the menu (for example a click event), the blur event of the input is always triggered first so the click event of the menu is never triggered
Here's a sample code to illustrate my problem: https://jsfiddle.net/f7xvg1L9/27/
function hide () {
document.getElementById('box').style.display = 'none';
}
function show () {
document.getElementById('box').style.display = 'block';
}
function select () {
document.getElementById('select').innerHTML = 'selected';
}
document.getElementById('input').addEventListener('blur', hide)
document.getElementById('input').addEventListener('focus', show)
document.getElementById('box').addEventListener('click', select)
#box {
width: 100px;
height: 50px;
background-color: red;
display: none;
}
<input type='text' id='input'/>
<div id='box'>Test</div>
<p id='select'></p>
(the select() function is never called)
Thanks in advance
You can do a lot of things in CSS instead of Javascript for this.
Here, setup a CSS rule for the selector input:focus + #box, #box:active, which displays the box.
#box:active is there to register the click on the box before it disappears, it won't work without it.
document.getElementById('box').addEventListener('click',() => {
document.getElementById('select').innerHTML = 'selected';
});
#box {
width: 100px;
height: 50px;
background-color: red;
display: none;
}
input:focus + #box, #box:active{
display: block;
}
<input type='text' id='input'/>
<div id='box'>
Test
</div>
<p id='select'></p>
That's an unfortunate side effect.
But it can be solved quite easily by using different events.
Instead of using a focus/blur handler, you can just use click events for all 3 of these, since focussing the input is the same as clicking inside it. And Blurring the input is the same as clicking outside of the input.
So if we show the box onclick of the input, we can then add a different click event to the rest of the document. Inside that click event, we can check if the current click is inside the box or not and act accordingly.
var box = document.getElementById('box');
var input = document.getElementById('input');
var change_text = function() {
box.innerHTML = 'selected';
};
var outside_click = function( event ) {
if ( !box.contains(event.target) ) {
box.style.display = 'none';
document.removeEventListener('click', outside_click);
}
};
var show_box = function( event ) {
event.stopPropagation();
box.style.display = 'block';
document.addEventListener('click', outside_click);
};
box.addEventListener('click', change_text);
input.addEventListener('click', show_box);
#box {
width: 100px;
height: 50px;
background-color: red;
display: none;
}
<input type='text' id='input'/>
<div id='box'>Test</div>
Edit: But the CSS solution posted above is a way better and easier solution.
Two things you can use:
event.relatedTarget - This is only valid for focus and blur events on only contains a value if the relatedTarget has tabindex=1 or greater.
the useCapture phase of addEventListener which allows you to get at events before most things get to them.
In the example below I use them both, though I really only needed to use the event.relatedTarget since that let me see that the user was clicking on the #box and prevent from closing the box.
function hide (evt) {
if (evt.relatedTarget && evt.relatedTarget.id === 'box') {
document.getElementById('box').style.display = 'none';
document.getElementById('input').focus();
}
else {
document.getElementById('box').style.display = 'none';
}
}
function show (evt) {
document.getElementById('box').style.display = 'block';
}
function select (evt) {
document.getElementById('select').innerHTML = 'selected';
}
document.getElementById('input').addEventListener('blur', hide);
document.getElementById('input').addEventListener('focus', show);
document.getElementById('box').addEventListener('click', select, true);
#box {
width: 100px;
height: 50px;
background-color: red;
display: none;
}
<input type="text" id="input"/>
<div id="box" tabindex="1">
Test
</div>
<p id="select"></p>
I think the most quick and simple way would be to use setTimeout in the hide function.
function hide () {
setTimeout(function(){
document.getElementById('box').style.display = 'none';
}, 300)
}
function show () {
document.getElementById('box').style.display = 'block';
}
function select () {
document.getElementById('select').innerHTML = 'selected';
}
document.getElementById('input').addEventListener('blur', hide)
document.getElementById('input').addEventListener('focus', show)
document.getElementById('box').addEventListener('click', select)
#box {
width: 100px;
height: 50px;
background-color: red;
display: none;
}
<input type='text' id='input'/>
<div id='box'>Test</div>
<p id='select'></p>

Events in javascript

I want to open a form on click of modify. I also want form to disappear when i click outside the form. When i use mouseleave event for that, the form is getting open and close automatically and i am failing to fill the form. I am not getting which event to use here.
JS
$(document).ready(function() {
$("#div1").load("compare-form-site.html");
});
$( ".m-search" ).click(function() {
$( "#modify" ).show( "blind",700 );
$( "#bank" ).hide();
$( ".slider" ).hide();
$( "#type" ).hide();
$( "#sort" ).hide();
});
$(".m-search").mouseleave(function(){
$('#modify').hide( );
});
HTML
<ul>
<li class="m-search">
Modify Search
<i class="fa fa-search-plus" aria-hidden="true">
</i>
<div id="modify" class="modify">
<div id="div1">
</div>
</div>
</li>
</ul>
You can compare to the target element and check if you click outside the form or in it. I f outside then hide the form.
$(document).on('click', function(e){
var $target = $('.modify');
if($target.is($(e.target)) && !$trigger.has(e.target).length) {
$('.modify').hide();
}
})
A working fiddle would be better for all to help you.
Here is an working example that should be help you:
// open the form
$('.modify').on('click', function(e) {
$(this).parent().find('.dialog').fadeIn();
});
// close the form (button inside form)
$('.close').on('click', function(e) {
$(this).parents('.dialog').fadeOut();
});
// hide the form if you click outside the form
$(document).mouseup(function (e) {
var container = $(".dialog");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
ul li button {
display: block;
}
.dialog {
display: none;
position: absolute;
top: 10%;
bottom: 10%;
left: 10%;
right: 10%;
background: blue;
}
.dialog .close {
float: right;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
Modifiy Search
<button class="modify">Test</button>
<div class="dialog">
<span class="close">Close me</span>
Im a test dialog
</div>
</li>
</ul>
mouseleave doesn't react on click but on the current pointer position. You have to add a click (mousedown) listener to e.g. document to listen to click events outside

Multiple show/hide buttons with button text change on click

i have a wordpress page with several buttons, that show/hide a certain div, also the button text changes from "more info" to "less info" according to button click.
This is my code so far, but as i have multiple buttons, of course each time i click on one, the code is executed for all hidden divs and button texts.
What has the code to be like, that it only affects the one button actually clicked / hidden div at a time?
Heres the HTML:
<a class="clicker reveal" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;">MORE INFOS</a>
and JS:
<script type="text/javascript">
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery(".slider").hide();
jQuery('.reveal').click(function() {
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
} else {
jQuery(this).text('MORE INFOS');
}
});
jQuery(".clicker").click(function(){
jQuery(".slider").slideToggle("slow");
jQuery.each(masterslider_instances, function(i, slider) {
slider.api.update();
slider.api.__resize(true);
jQuery.each(slider.controls, function( index, control ) {
if (control.realignThumbs) control.realignThumbs();
});
jQuery.each(masterslider_instances, function(a,b){
b.api.update(true);
});
});
});
});
</script>
and the targeted div:
<div class="slider>Some content</div>
Thank you in advance!
UPDATE
I am informed that the button is in a div, the update reflects that small change:
From:
var tgt = $(this).next('.slider');
To:
var tgt = $(this).parent().next('.slider');
The following demo uses the class methods. Details are provided within the source in the comments.
SNIPPET
/*
Removed a chunk of meaningless code
since there's no way of using it
because the plugin isn't
provided (I'm assuming).
*/
$(function() {
/*
Combined both the `more/less` and
`slideToggle()` features under one
class(`.reveal`) and one click event.
*/
$('.reveal').on('click', function(e) {
/*
Prevent anchor from default behavior
of jumping to a location.
*/
e.preventDefault();
/*
See if `.reveal` has class `.more`
*/
var more = $(this).hasClass('more');
/*
`.tgt` is the next `.slider` after
`this`(clicked `a.reveal`).
*/
var tgt = $(this).parent().next('.slider');
/*
Toggle `.reveal`'s state between `.more` and
`.less` classes. (See CSS)
*/
if (more) {
$(this).removeClass('more').addClass('less');
} else {
$(this).removeClass('less').addClass('more');
}
/*
`slideToggle()` only the `div.slider` that
follows `this` (clicked `a.reveal`)
*/
tgt.slideToggle('slow');
});
});
.reveal {
display: block;
}
.reveal.more:before {
content: 'MORE INFO';
}
.reveal.less:before {
content: 'LESS INFO';
}
.slider {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
Try this
jQuery('.reveal').each(function(idx,item) {
jQuery(item).click(function(){
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
}
else {
jQuery(this).text('MORE INFOS');
}
});
});
Here is working Fiddle
Make a reference between the anchor and div by using data attribute.
<a class="clicker reveal" data-target="slider-1" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;">MORE INFOS</a>
<div class="slider slider-1">Some content</div>
Now, you can do the following-
jQuery('.clicker').click(function() {
var targetDiv = jQuery('.' + jQuery(this).attr('data-target'))
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
targetDiv.slideDown('slow');
} else {
jQuery(this).text('MORE INFOS');
targetDiv.slideUp('slow');
}
// do the rest of your stuff here
});

How to make sure a click event has an effect only on the intended class?

Here is the important part of the code that executes.
Im trying to click on one element with a particular ID that relates to bookmarking the message but the element keeps triggering another click event that hides every div with the class 'messageCase' while at the same time attaching class messageOpen2 to the bookmark images ID which is very odd
the 'hidden' classes just hide all other message instances that contain
The messageCase class.
var openMessageAnimationStrategy = function () {
var openMessage = $(document).ready(function () {
var divTarget = $("div.messageCase");
$(divTarget).click(function (e) {
var target = $(e.target);
target.toggleClass('messageOpen2');
divTarget.addClass('hidden');
target.removeClass('hidden');
});
});
};
Here is what the HTML looks like
<div class="messageCase">
<div class="messageImageBox">
<div id="messageImage">
</div>
</div>
<div id="subjectLine">
Subject Line Text
</div>
<div id="bookMarkImage">
<img id="bookmarkStatus" class="savedMessage" src="notbookMarked64.png" />
</div>
<div class="activeBookmarks">
{38} <br />
Bookmarks <br />
<br />
9:53am
</div>
<div id="bodyPreview">
Body Preview Text is light
</div>
</div>
Every Time I use the Click event on bookmarkStatus to change the src of the image it causes the first click event to execute making everything disappear & the class messageOpen2 to be added to bookmarkStatus. I can include the CSS if necessary but ill list the code for the bookmarking function below
var bookmarkedStrategy = function () {
var bookmarkedStrategy = $(document).ready(function () {
var bookmarkStatus = $("#bookmarkStatus");
var divTarget = $('messageCase');
//below trying to remove the Class that was attached by the initial function while also changing the image SRC for the class bookmark
$(divTarget).click(function (e) {
var target = $(e.target);
divTarget.removeClass('messageCase2');
bookmarkStatus.toggleClass('savedMessage');
});
});
};
I Think the main problem has to do with the initial function but I don't know what else could be wrong any ideas?
edit Here is the CSS that matters.
.savedMessage {
background-image: url("bookmarked64.png");
}
.messageOpen2 {
height: 250px;
}
.messageCase {
margin: 5px;
border-radius: 5px;
background-color: aliceblue;
height: 70px;
}
#bookMarkImage {
float:right;
height:64px;
width:64px;
z-index:9999;
}
.hidden {
display:none;
max-height: inherit;
}
.activeBookmarks {
float: right;
text-align: center;
font-size: 13px;
font-weight: 700;
text-decoration: solid;
}
Calling code
var bookmarkedthings = new MessageHandling(bookmarkedStrategy);
bookmarkedthings.greet();
var openMessage = new MessageHandling(openMessageAnimationStrategy);
openMessage.greet();
There is a missing . in your bookmarkedStrategy function code var divTarget = $('.messageCase'); Add dot and try again

Scroll to top button showing when not on top of the page

I would like to have a scroll to top arrow fixed in my page using angular bootstrap.
Currently I have
<div class="col-md-1">
<div class="affix">
<div>
<a th:href="#{/}" href="#" target="_self"><img id="image" src="source" alt="yoli" width="50px" /></a>
</div>
Scroll to top
</div>
</div>
<div class="col-md-6">
<div id="search-bar" ng-include="blabla"></div>
<li ng-repeat="something"></li>
</div>
However when the "Scroll to top" is click it only works first time since the url changes to ...#search-bar and when you click it again nothing happens. So how do I scroll to top without changing the url?
And also question how do I make the "Scroll to top" only show when the search-bar is not showing?
I was thinking about using $anchorScroll and using id'ed numbers on li and if it's higher then "element-3" then show the button, however not sure if that would work.
UPDATE:
I am thinking of following this example, that is using navigation bars that is #search and #results and make the #search href visible on #results active and #results one hidden.
You can do this without jQuery as well:
function filterPath(string) {
return string
.replace(/^\//, '')
.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
.replace(/\/$/, '');
}
const locationPath = filterPath(location.pathname);
document.querySelectorAll('a[href*="#"]').forEach(link => {
let thisPath = filterPath(link.pathname) || locationPath;
if ((location.hostname == link.hostname || !link.hostname)
&& (locationPath == thisPath)
) {
let hashName = link.hash.replace(/#/, '');
if (hashName) {
let targetEl = document.getElementById(hashName);
if (targetEl) {
link.addEventListener('click', () => {
event.preventDefault();
targetEl.scrollIntoView({
top: 50,
left: 0,
behavior: "smooth"
});
});
}
}
}
});
Here is how you can do it. Create a button:
Scroll To Top
CSS:
.scrollToTop{
width:100px;
height:130px;
padding:10px;
text-align:center;
background: whiteSmoke;
font-weight: bold;
color: #444;
text-decoration: none;
position:fixed;
top:75px;
right:40px;
display:none;
background: url('arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
text-decoration:none;
}
JavaScript:
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
You can find a demo here. The source presented is taken from here.

Categories

Resources