event.target does not work for properly in jQuery code - javascript

I am stuck with the following simple code.
$(function() {
'use strict';
function header() {
var openButton = $('.search_button'),
box = $('.box'),
closeButton = $('.close');
box.hide();
function init() {
initEvents();
}
function initEvents() {
openButton.on('click', openBox);
$(document).on('keyup', function(event) {
if(event.keyCode === 27) {
box.slideUp('normal');
}
});
}
function openBox(event) {
if(event.target === closeButton[0]) {
box.hide();
} else if(event.target === openButton[0] || $(event.target).closest(box).length) {
box.show();
}
else {
box.hide();
}
}
init();
}
header();
});
.box {
width:500px;
height:500px;
background-color:red;
position:relative;
}
.close {
width:80px;
height:80px;
background-color:orange;
position:absolute;
top:0;
right:0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header_search">
<form action="search.php" method="post">
<input type="text" placeholder="" id="main_search" class="search_button">
</form>
</div>
<div class='box'>
<div class='close'></div>
</div>
My intension is that, when I click outside the DIV, it closes and the 'close' DIV on click closes the red main div.
The code, slidesDown the box div and escape key slideup as well.
But close and clicking outside to close the red div does not work.
Could someone assist me with the code with some explanation
Thanks and regards
Jeff

You are using the event handler click only in the .search_button, you have to use it in your body.
function initEvents() {
$(body:not('#header_search')).on('click', openBox);
$(document).on('keyup', function(event) {
if(event.keyCode === 27) {
box.slideUp('normal');
}
});
}

Related

Input toggle focus hiding submit button when trying to click it

I have a form that if you click on the input field giving it focus the submit button displays.
However the issue I'm having is that when you try to click on the submit button it disappears as the focus has been removed from the input.
Here is my code:
<form method="post" id="subForm" class="clearfix">
<input id="fieldEmail" placeholder="email address" type="email"/>
<button type="submit"><i class="arrow"></i></button>
</form>
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
$(this).next().removeClass('visible');
});
And here is a JSFiddle
What is the best way to keep the toggling of class 'visible' but allow me to click the submit button?
It has to do with the order of events.
You can use mousedown to detect where the focus moves to because it triggers before the blur:
(function () {
var submit_focus = false;
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if (submit_focus) {
submit_focus = true;
} else {
$(this).next().removeClass('visible');
}
});
$('#submit').mousedown(function () {
submit_focus = true;
});
}());
http://jsfiddle.net/cnLon9k3/4/
I suggest to put a check inside the function which hides the button and see if the input field has some value (if yes, you wouldn´t want to hide the button, or?)
e.g:
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if($(this).val() === ""){
$(this).next().removeClass('visible');
}
});
We can have a check that on blur of textfield, the new focused element is button or not.
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if(!event.relatedTarget||event.relatedTarget.type!='submit')
$(this).next().removeClass('visible');
});
form {
color:#333;
position: relative;
}
input {
padding:0 5px 5px;
text-align: center;
border:none;
text-transform: uppercase;
font-size:12px;
width:170px;
margin-left:15px;
float:left;
letter-spacing: 2px;
}
button {
display: none;
background: #ff0000;
border:none;
}
.arrow {
background:#ff0000;
width:15px;
height:15px;
display: block;
}
.visible {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="subForm" class="clearfix">
<input id="fieldEmail" placeholder="email address" type="email"/>
<button type="submit"><i class="arrow"></i></button>
</form>
I would suggest to capture each click event on document and if the target of that event is not submit button or email input then hide the submit button as below and remove the blur event from input
$(document).on('click',function(e){
if(e.target.type!="submit" && e.target.type !="email")
{
$('#fieldEmail').next().removeClass('visible')
}
});
DEMO HERE

How to hide a div when the user clicks body

I am using this code:
function check_remember(event) {
if (document.getElementById('rem_email').value == "") {
alert("Harap isi email !");
} else {
document.getElementById('popup_remember').style.display = "none";
event.preventDefault();
}
};
function remember_show() {
document.getElementById('popup_remember').style.display = "block";
};
and this my html :
<button type="button" class="btn-custom remember" onclick="remember_show()">Ingatkan Saya</button>
<!-- PopUp -->
<div id="popup_remember">
<div id="REM">
<form id="form_remember">
<input id="rem_email" name="email" placeholder="Input Email" type="text" class="form-control" required>
<input type="submit" id="sub_rem" value="Agree" onclick="check_remember(event)">
</form>
</div>
</div>
The problem is, i do not know how to when click body modal will hide..
I think this is what you looking for:
WORKING : DEMO
UPDATED DEMO
HTML
<h1> Just Random Header </h1>
<div class="div1"> Hello i am div :) <br /> <br />If you click anywhere then me i will disappear !</div>
CSS
.div1
{
width:310px;
height:100px;
background:#ddd;
}
JS
$(document).mouseup(function (e)
{
var container = $(".div1");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
First get clicked target. Then check if the click event is out of popup div and if it is hidden already. Something like this should work:
$(function(){
$('body').on('click', function(){
var $this = $(arguments[0].target);
var $target = $('#popup_remember');
if( !$this.parents('#popup_remember').length && $this.attr('id') != "REM" && $target.is(':visible') ) $target.hide();
});
});
Check jsFiddle
You could try using jQuery instead of just Javascript.
$(document).ready(function(){
$('body').on('click', function(){
if($('#rem_email').val() === ''){
alert('Harap isi email !');
} else {
$('#popup_remember').hide()
}
}
//Let's add your remember_show function too! It's also an OnClick (As seen in the HTML).
$('btn-custom remember').on('click',function(){
$('popup_remember').show();
});
});
That's your javascript code converted to jQuery. :)
Instead of hide() and show(), you can also use fadeOut() and fadeIn() to animate the opacity of the object you are hiding and showing.
If your trying to make custom modal this may helps you. But this is only for the modal effect and your problem about clicking the body and it will close the modal. JS Fiddle Link
Hope it helps. Happy Coding.
you can use javascript too:
<button type="button" class="btn-custom remember" onclick="remember_show(event)">Ingatkan Saya</button>
Pass the event in the arguments of the calling function. Then you need to add event.stopPropagation(); to stop the event to bubble up in the DOM tree.
function check_remember(event) {
if (document.getElementById('rem_email').value == "") {
alert("Harap isi email !");
} else {
document.getElementById('popup_remember').style.display = "none";
event.preventDefault();
}
event.stopPropagation(); //<----add this to stop the event to bubble up.
};
function remember_show(event) {
document.getElementById('popup_remember').style.display = "block";
event.stopPropagation(); //<----add this to stop the event to bubble up.
};
Now add a event listener on the body like:
function hideModal(e){
document.getElementById('popup_remember').style.display = "none";
event.stopPropagation();
}
document.addEventListener('click', hideModal, false);
Sample Demo:
function check_remember(event) {
if (document.getElementById('rem_email').value == "") {
alert("Harap isi email !");
} else {
document.getElementById('popup_remember').style.display = "none";
event.preventDefault();
}
event.stopPropagation();
};
function remember_show(event) {
document.getElementById('popup_remember').style.display = "block";
event.stopPropagation();
};
function hideModal(e) {
document.getElementById('popup_remember').style.display = "none";
event.stopPropagation();
}
var body = document;
body.addEventListener('click', hideModal, false);
#popup_remember {
display: none;
}
<button type="button" class="btn-custom remember" onclick="remember_show(event)">Ingatkan Saya</button>
<!-- PopUp -->
<div id="popup_remember">
<div id="REM">
<form id="form_remember">
<input id="rem_email" name="email" placeholder="Input Email" type="text" class="form-control" required>
<input type="submit" id="sub_rem" value="Agree" onclick="check_remember(event)">
</form>
</div>
</div>

CSS Slide Down and Slide Up on document click

I have a issue here. I'm trying to do the slideUp and slideDown equivalent in CSS3 transitions but also want when document is clicked the div element slides up.
Here is the code
http://jsfiddle.net/RK8FZ/2/
HTML
<div id="main">
<div id="search-content">
<input type="search" placeholder="Search"/>
<input type="submit" />
</div>
<section class="wrapper">
<span id="toggle-search">Search</span>
</section>
</div>
Here is the CSS code
#main #search-content { position: relative; max-height: 0; overflow: hidden; transition: all .3s linear; background: #FFF; opacity: 0;}
#main #search-content.open { max-height: 200px; opacity: 1; }
Here is the jquery code
function toggleSearch() {
$('#toggle-search').on('click', function(event){
$('#search-content').toggleClass('open').find('input[type="search"]').focus();
$(this).text( $(this).text() === "Search" ? "Close" : "Search" );
})
$('#search-content').on ('click', function(e) {
e.stopPropagation();
});
$(document).on('click', function() {
if( $('#search-content').hasClass('open') ) {
$('#search-content').removeClass('open');
}
});
}
Can anyone figure this thing out? What it is happening is that it triggers the open and the close at the same instante.
Working DEMO
I guess this is what you need
$(function () {
toggleSearch();
})
function toggleSearch() {
$('#toggle-search').on('click', function (event) {
event.stopPropagation();
$('#search-content').toggleClass('open').find('input[type="search"]').focus();
$(this).text($(this).text() === "Search" ? "Close" : "Search");
})
}
$(document).on('click', function (e) {
$('#toggle-search').text('Close');
$('#search-content').removeClass('open');
});
$('#search-content').on('click', function (e) {
e.stopPropagation();
});
$(document).on('click', function () {
if ($(this).addClass('search-open')) {
$('#search-content').removeClass('open');
}
});
What are you checking in if condition? If you wan to check if search-open class exists then you can use
if ($(.search-open').length > 0)

How to close div clicking outside of it [duplicate]

This question already has answers here:
Use jQuery to hide a DIV when the user clicks outside of it
(40 answers)
Closed 9 years ago.
Now I am closing the alert box when I clicked on the 'x' but I want to close the alertbox when I click outside of it.
Please see my code here :http://jsfiddle.net/Ur5Xn/
How to close alertbox clicking outside of it?
The jQuery:
$(document).ready(function(){
function showAlertBox(){
$("#alert").css("display","inherit");
$("#content").addClass("back");
}
function removeAlertBox(){
$("#alert").css("display","none");
$("#content").removeClass("back");
}
$("#alertClose").click(function(){
removeAlertBox();
});
$("#alertShow").click(function(){
showAlertBox();
});
});
try this code
$(document).ready(function(){
function showAlertBox(){
$("#alert").css("display","inherit");
$("#content").addClass("back");
}
function removeAlertBox(){
$("#alert").css("display","none");
$("#content").removeClass("back");
}
$("#alertClose").click(function(e){
e.stopPropagation();
removeAlertBox();
});
$("#alertShow").click(function(e){
e.stopPropagation();
showAlertBox();
});
$(document).click(function(e){
removeAlertBox();
});
});
This should work: http://jsfiddle.net/LagBE/
$(document).on('mouseup', function (e)
{
var alert = $('#alert');
// Make sure neither the alert,
// nor anything inside of it was clicked
if (!alert.is(e.target) && alert.has(e.target).length === 0)
{
removeAlertBox();
}
});
jsfiddle here
html:
<div id="alert">
<div id='transBG'></div>
<div id="alertbox">I am an alert box <span id="alertClose">X</span></div>
</div>
<div id="content">
Content <span id="alertShow">Show Alert Box</span>
</div>
css:
#alert {
display:none;
}
#alertbox{
border:1px solid #000;
position:fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
height:100px;
width:200px;
z-index:9;
}
#transBG{
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
z-index:8;
}
.back{
opacity:0.5;
}
javascript:
$(document).ready(function(){
function showAlertBox(){
$("#alert").css("display","inherit");
$("#content").addClass("back");
}
function removeAlertBox(){
$("#alert").css("display","none");
$("#content").removeClass("back");
}
$("#transBG").click(function(){
removeAlertBox();
});
$("#alertClose").click(function(){
removeAlertBox();
});
$("#alertShow").click(function(){
showAlertBox();
});
});
Here is the update working code:
$(document).ready(function () {
function showAlertBox() {
$("#alert").css("display", "inherit");
$("#content").addClass("back");
return false;
}
function removeAlertBox() {
$("#alert").css("display", "none");
$("#content").removeClass("back");
return false;
}
$("#alertClose").click(removeAlertBox);
$("#alertShow").click(showAlertBox);
$('#alert').click(false);
$(document).click(removeAlertBox);
});
See http://jsfiddle.net/Ur5Xn/34/

Change div text with jQuery Toggle

When using slideToggle, how to change the Text close/show?
I did a simple one, but cannot get the text change back.
Here is what I did:
$(document).ready(function(){
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
});
$('.open2').click(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
});
});
body{
font-size:20px;
}
#box{
border:2px solid #000;
width:500px;
min-height:300px;
}
.open,.open2 {
width:450px;
height:50px;
background:blue;
margin:5px auto 0 auto;
color:#fff;
}
.showpanel,.showpanel2{
width:450px;
height:300px;
margin:0 auto 10px auto;
background:red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div class="open">Show</div>
<div class="showpanel">This is content</div>
<div class="open2">Show</div>
<div class="showpanel2">This is content</div>
</div>
http://jsfiddle.net/9EFNK/
You can use the is() assertion method to check whether the panel is open or closed in the animation's callback and set the text accordingly - http://jsfiddle.net/9EFNK/7/
$('.open').click(function(){
var link = $(this);
$('.showpanel').slideToggle('slow', function() {
if ($(this).is(':visible')) {
link.text('close');
} else {
link.text('open');
}
});
});
Just add a simple if statement to test the text like so
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
if($(this).text() == 'close'){
$(this).text('Show');
} else {
$(this).text('close');
}
});
Like this DEMO
Not the prettiest of methods, but it does the job in a single statement.
$(this).text(($(this).text() == 'Close') ? 'Show' : 'Close');
Use .toggle()
Here is Working Demo
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
}).toggle(function() {
$(this).text('Hide');
}, function() {
$(this).text('Show');
});
check this may be user question is solve Fiddle
Here's an updated version http://jsfiddle.net/9EFNK/1/
You can simply toggle a class on close/open, perform a check for that class and change the contained text accordingly
if( $(this).hasClass('active') )
$(this).text('open');
else
$(this).text('Show');
$(this).toggleClass('active');
try this demo
$(document).ready(function(){
$('.open').toggle(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel').slideToggle('slow');
$(this).text('Show');
});
$('.open2').toggle(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel2').slideToggle('slow');
$(this).text('Show');
});
});​
Use this
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
Here is how you use it
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
$('[data-toggle="offcanvas"]').click(function () {
$(this).toggleText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>
You can even use html provided it's html encoded properly

Categories