Input toggle focus hiding submit button when trying to click it - javascript

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

Related

Blur/unblur action on input clearance

I have the situation where I want to blur and unblur a background dynamically based on the inclusion of text in an input.
The unblur happens nicely, however, the re-blur on clearance of the input is not working? Not sure if I've just been staring at this too long, but hitting up SO because I'm slowly going insane looking at this. Thanks in advance for any help!
Code below:
<div>
<form name="search" class="searchBarClass" action="/action_page.php" style="margin:auto;max-width:300px">
<input type="text" placeholder="Search.." name="searchInput" onkeyup="unblur();blur();">
<button type="submit"><span class="material-icons">search</span></button>
</form>
</div>
<div id="background"></div>
Script for update:
function unblur() {
document.getElementById("background").style.filter = "none";
}
function blur() {
var x = document.forms["search"]["searchInput"].value;
if (x === "") {
document.getElementById("map").style.filter = "blur(2px)";
}
}
The intention is to blur the background whenever the input is empty. Here's some minimal code that accomplishes that:
const bgDiv = document.getElementById("background");
// blur background image when input is empty
function blurOnEmptyInput() {
var x = document.forms["search"]["searchInput"].value;
if (x === "") {
bgDiv.classList.add('blur');
} else {
bgDiv.classList.remove('blur');
}
}
/* style with CSS instead of embedding in JavaScript function */
.bg-image {
background-image: url("https://picsum.photos/300/100");
height: 100px;
width: 300px;
border: 1px solid gray;
}
.blur {
filter: blur(2px);
}
div {
margin: 1rem 0 0 1rem;
}
<div>
<form name="search">
<input placeholder="Search.." name="searchInput"
onkeyup="blurOnEmptyInput();">
</form>
</div>
<div id="background" class="bg-image blur"></div>

event.target does not work for properly in jQuery code

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');
}
});
}

Adding Overlay to a popup and adding input type field to exit the form

I have been working on creating a popup with some different functionality. It is being used as a pop for users to subscribe to my website. I have added in a form connected my DB, which is all working great. I am now trying to add some custom features.
I am trying to add some overlay (faded) to my background of the popup so my homepage is faded out in the background of the popup
I need to add in a input type field (if possible) to close my form. * I have added in a image with a X, if there is not input type option I will use this to exit the form
Here is my code:
JavaScript:
<script>
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') {
document.getElementById('ac-wrapper').style.display = "none";
}
else if(localStorage.getItem("popupWasShown") == null) {
localStorage.setItem("popupWasShown",1);
document.getElementById('ac-wrapper').removeAttribute('style');
}
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
HTML:
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
<div id="popup">
<img alt="#" class="close-image" src="Assets/images/Deep_Close.png" />
<form name="Mail_list" action="save.php" method="post">
<br/>
<h4>Subscription</h4>
<br/>
<div class="form-group">
<label for="first_name">First Name: </label>
<input type="text" name="first_name" id="first_name" size="25" placeholder="First Name" autofocus required />
</div>
<div class="form-group">
<label for="last_name">Last Name: </label>
<input type="text" name="last_name" id="last_name" size="25" placeholder="Last Name" required />
</div>
<div class="form-group">
<label for="email">User Email: </label>
<input type="text" name="email" id="email" size="25" placeholder="Email" required />
</div>
<br/><br/>
<input type="submit" value="Submit Form">
<input type="reset" value="Reset Form">
</form>
CSS:
#ac-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1001;
}
#popup{
position:absolute;
display:hidden;
top:300px;
left:50%;
width:500px;
height:auto;
margin-left:-250px;
background-color:white;
z-index:6;
padding:20px;
border:solid 5px #333333;
border-radius:5px;
}
#overlay-back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
opacity: 0.6;
filter: alpha(opacity=60);
z-index: 5;
display: none
}
.close-image{
display: block;
float:right;
position:relative;
top:-15px;
right: -15px;
height: 20px;
}
As you can see I have added in the 'Overlay' CSS already, I just am not sure how to implement this in my popup to make the functionality work.
Also, the 'close-image' CSS will be used to close the form if their is no input type available to close the form (which I haven't been able to find), How do I implement this is my JavaScript?
For the overlay, give it position: fixed and place it outside of your other elements. You want it to be 'fixed' to the body, so with 100% height and width it'll cover the full page, effectively.
Just build your overlay/ form to look how you want - with all elements visible, then handle the show/ hide afterwards in your JavaScript.
To close the form, just have a click handler to hide both the form and the overlay when the given element is clicked. See a brief example:
var closeImage = document.getElementById('close-image');
var overlay = document.getElementById('overlay-back');
var formWrapper = document.getElementById('ac-form-wrapper');
// Hide the elements & do other stuff you may want..
function hide() {
overlay.style.display = "none";
formWrapper.style.display = "none";
}
// Call this whenever you want to show stuff.
// In this case, it would go inside the setTimeout
// function also.
function show() {
overlay.style.display = "block";
formWrapper.style.display = "block";
}
// Click handler for the image element.
closeImage.addEventListener("click", function() {
hide();
}, false);
It may be better to change the close-image element to be an ID instead, it's easier to target in native JavaScript, and the element probably doesn't need to be a class anyway.

To-Do list with edit button Jquery

I'm trying to make a to-do list with an edit button, that when clicked, will make added items editable, but am having trouble. I have the button created and everything, but when I click it nothing happens. Any advice would be greatly appreciated!
JavaScript
function editItem(){
var parent = $(this).parent();
if (!parent.hasClass('edit')) {
parent.addClass('edit');
}else if (parent.hasClass('edit')) {
var editTask = $(this).prev('input[type="text"]').val();
var editLabel = parent.find('label');
editLabel.html(editTask);
parent.removeClass('edit');
}
$(function(){
$(document).on('click', 'edit', editItem)
});
Looks like you are targeting <edit>, you are supposed to use .edit:
$(function(){
$(document).on('click', '.edit', editItem);
});
Working Snippet
$(function () {
function addItem () {
// append to the list
$("#todo-items").append('<li><span>' + $("#todo").val() + '</span> <small>Edit • Delete</small></li>');
// clear the text
$("#todo").val("");
}
$("#todo").keydown(function (e) {
// if enter key pressed
if (e.which == 13)
addItem();
});
// on clicking the add button
$("#add").click(addItem);
// delegate the events to dynamically generated elements
// for the edit button
$(document).on("click", 'a[href="#edit"]', function () {
// make the span editable and focus it
$(this).closest("li").find("span").prop("contenteditable", true).focus();
return false;
});
// for the delete button
$(document).on("click", 'a[href="#delete"]', function () {
// remove the list item
$(this).closest("li").fadeOut(function () {
$(this).remove();
});
return false;
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none; text-decoration: none;}
input, li {padding: 3px;}
#todo-items small {display: inline-block; margin-left: 10px; padding: 2px; vertical-align: bottom;}
#todo-items span:focus {background-color: #ccf;}
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<input type="text" id="todo" />
<input type="button" value="Add" id="add" />
<ul id="todo-items"></ul>

javascript search function not working

I have a search form which which takes an input and pass the data to a django view.
the form has a search button which on click opens a input box like shown in images given below:
Now when i enter something into the input and press enter, it just collapses the input box and no action occurs. It happens every time. I want it to call the function associated with form. I figured out that the problem is in the javascript but don't know how to fix it.
html:
<form class="navbar-form" role="search" method="POST" action="{% url 'search' %}">
{% csrf_token %}
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="search_box">
<span class="input-group-btn">
<button name="search" type="submit" class="search-btn"> <span class="glyphicon glyphicon-search"> <span class="sr-only">Search</span> </span> </button>
</span>
</div>
</form>
javascript:
e(function() {
function t() {
var t = e('.navbar-collapse form[role="search"].active');
t.find("input").val(""), t.removeClass("active")
}
e('header, .navbar-collapse form[role="search"] button[type="reset"]').on("click keyup", function(n) {
console.log(n.currentTarget), (27 == n.which && e('.navbar-collapse form[role="search"]').hasClass("active") || "reset" == e(n.currentTarget).attr("type")) && t()
}), e(document).on("click", '.navbar-collapse form[role="search"]:not(.active) button[type="submit"]', function(t) {
t.preventDefault();
var n = e(this).closest("form"),
i = n.find("input");
n.addClass("active"), i.focus()
}), e(document).on("click", '.navbar-collapse form[role="search"].active button[type="submit"]', function(n) {
n.preventDefault();
var i = e(this).closest("form"),
s = i.find("input");
e("#showSearchTerm").text(s.val()), t()
})
}
css:
.navbar-collapse form[role="search"] input {
font-size: 18pt;
opacity: 0;
display: none;
height: 48px;
position: relative;
z-index: 2;
float: left;
}
.navbar-collapse form[role="search"].active input {
display: table-cell;
opacity: 1;
z-index: 100;
border-radius: 0;
border: none;
line-height: 45px;
height: 75px;
font-size: 14px;
padding: 0px 25px;
width: 315px;
}
.navbar-collapse {float:right; padding:0px}
its because you didn't submit form
Try this to submit form..
Without AJAX
$('form#myForm').submit();
with performing AJAX
$('input#submitButton').click( function() {
$.post( 'some-url', $('form#myForm').serialize(), function(data) {
... do something with response from server
},
'json' // I expect a JSON response
);
});
$('input#submitButton').click( function() {
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
... do something with the data...
}
});
});
Hope this helps..
Letting you know the step by step procedure.
Set a .keyup event on the search input. $("[name='search_box']").keyup(function(e){ .... });
Check if the keycode of the pressed key is equal to 13 (enter key) if(e.keyCode==13){ ... }
If it is 13 then call the function associated with the form.

Categories