I am going to make a button to take an action and save the data into a database.
Once the user clicks on the button, I want a JavaScript alert to offer “yes” and “cancel” options. If the user selects “yes”, the data will be inserted into the database, otherwise no action will be taken.
How do I display such a dialog?
You’re probably looking for confirm(), which displays a prompt and returns true or false based on what the user decided:
if (confirm('Are you sure you want to save this thing into the database?')) {
// Save it!
console.log('Thing was saved to the database.');
} else {
// Do nothing!
console.log('Thing was not saved to the database.');
}
var answer = window.confirm("Save data?");
if (answer) {
//some code
}
else {
//some code
}
Use window.confirm instead of alert. This is the easiest way to achieve that functionality.
How to do this using 'inline' JavaScript:
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go"
onclick="return confirm('Are you sure you want to search Google?')"
/>
</form>
Avoid inline JavaScript - changing the behaviour would mean editing every instance of the code, and it isn’t pretty!
A much cleaner way is to use a data attribute on the element, such as data-confirm="Your message here". My code below supports the following actions, including dynamically-generated elements:
a and button clicks
form submits
option selects
jQuery:
$(document).on('click', ':not(form)[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('submit', 'form[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('input', 'select', function(e){
var msg = $(this).children('option:selected').data('confirm');
if(msg != undefined && !confirm(msg)){
$(this)[0].selectedIndex = 0;
}
});
HTML:
<!-- hyperlink example -->
Anchor
<!-- button example -->
<button type="button" data-confirm="Are you sure you want to click the button?">Button</button>
<!-- form example -->
<form action="http://www.example.com" data-confirm="Are you sure you want to submit the form?">
<button type="submit">Submit</button>
</form>
<!-- select option example -->
<select>
<option>Select an option:</option>
<option data-confirm="Are you want to select this option?">Here</option>
</select>
JSFiddle demo
You have to create a custom confirmBox. It is not possible to change the buttons in the dialog displayed by the confirm function.
jQuery confirmBox
See this example: https://jsfiddle.net/kevalbhatt18/6uauqLn6/
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// Do nothing
});
Pure JavaScript confirmBox
Example: http://jsfiddle.net/kevalbhatt18/qwkzw3rg/127/
<div id="id_confrmdiv">confirmation
<button id="id_truebtn">Yes</button>
<button id="id_falsebtn">No</button>
</div>
<button onclick="doSomething()">submit</button>
Script
<script>
function doSomething(){
document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line
document.getElementById('id_truebtn').onclick = function(){
// Do your delete operation
alert('true');
};
document.getElementById('id_falsebtn').onclick = function(){
alert('false');
return false;
};
}
</script>
CSS
body { font-family: sans-serif; }
#id_confrmdiv
{
display: none;
background-color: #eee;
border-radius: 5px;
border: 1px solid #aaa;
position: fixed;
width: 300px;
left: 50%;
margin-left: -150px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#id_confrmdiv button {
background-color: #ccc;
display: inline-block;
border-radius: 3px;
border: 1px solid #aaa;
padding: 2px;
text-align: center;
width: 80px;
cursor: pointer;
}
#id_confrmdiv .button:hover
{
background-color: #ddd;
}
#confirmBox .message
{
text-align: left;
margin-bottom: 8px;
}
Or simply:
click me!
This plugin can help you jquery-confirm easy to use
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
confirm: function(){
alert('Confirmed!');
},
cancel: function(){
alert('Canceled!')
}
});
This a full responsive solution using vanilla javascript :
// Call function when show dialog btn is clicked
document.getElementById("btn-show-dialog").onclick = function(){show_dialog()};
var overlayme = document.getElementById("dialog-container");
function show_dialog() {
/* A function to show the dialog window */
overlayme.style.display = "block";
}
// If confirm btn is clicked , the function confim() is executed
document.getElementById("confirm").onclick = function(){confirm()};
function confirm() {
/* code executed if confirm is clicked */
overlayme.style.display = "none";
}
// If cancel btn is clicked , the function cancel() is executed
document.getElementById("cancel").onclick = function(){cancel()};
function cancel() {
/* code executed if cancel is clicked */
overlayme.style.display = "none";
}
.popup {
width: 80%;
padding: 15px;
left: 0;
margin-left: 5%;
border: 1px solid rgb(1,82,73);
border-radius: 10px;
color: rgb(1,82,73);
background: white;
position: absolute;
top: 15%;
box-shadow: 5px 5px 5px #000;
z-index: 10001;
font-weight: 700;
text-align: center;
}
.overlay {
position: fixed;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,.85);
z-index: 10000;
display :none;
}
#media (min-width: 768px) {
.popup {
width: 66.66666666%;
margin-left: 16.666666%;
}
}
#media (min-width: 992px) {
.popup {
width: 80%;
margin-left: 25%;
}
}
#media (min-width: 1200px) {
.popup {
width: 33.33333%;
margin-left: 33.33333%;
}
}
.dialog-btn {
background-color:#44B78B;
color: white;
font-weight: 700;
border: 1px solid #44B78B;
border-radius: 10px;
height: 30px;
width: 30%;
}
.dialog-btn:hover {
background-color:#015249;
cursor: pointer;
}
<div id="content_1" class="content_dialog">
<p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
<p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.</p>
</div>
<button id="btn-show-dialog">Ok</button>
<div class="overlay" id="dialog-container">
<div class="popup">
<p>This will be saved. Continue ?</p>
<div class="text-right">
<button class="dialog-btn btn-cancel" id="cancel">Cancel</button>
<button class="dialog-btn btn-primary" id="confirm">Ok</button>
</div>
</div>
</div>
You can intercept the onSubmit event using JavaScript.
Then call a confirmation alert and then grab the result.
Another way to do this:
$("input[name='savedata']").click(function(e){
var r = confirm("Are you sure you want to save now?");
//cancel clicked : stop button default action
if (r === false) {
return false;
}
//action continues, saves in database, no need for more code
});
xdialog provides a simple API xdialog.confirm(). Code snippet is following. More demos can be found here
document.getElementById('test').addEventListener('click', test);
function test() {
xdialog.confirm('Are you sure?', function() {
// do work here if ok/yes selected...
console.info('Done!');
}, {
style: 'width:420px;font-size:0.8rem;',
buttons: {
ok: 'yes text',
cancel: 'no text'
},
oncancel: function() {
console.warn('Cancelled!');
}
});
}
<link href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog#3/xdialog.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog#3/xdialog.min.js"></script>
<button id="test">test</button>
Made super simple, tiny vanilla js confirm dialog with Yes and No buttons.
It's a pity we can't customize the native one.
https://www.npmjs.com/package/yesno-dialog.
Another solution apart from the others is to use the new dialog element. You need to make use of show or showModal methods based on interactivity with other elements. close method can be used for closing the open dialog box.
<dialog>
<button class="yes">Yes</button>
<button class="no">No</button>
</dialog>
const dialogEl = document.querySelector("dialog");
const openDialog = document.querySelector("button.open-dialog");
const yesBtn = document.querySelector(".yes");
const noBtn = document.querySelector(".no");
const result = document.querySelector(".result");
openDialog.addEventListener("click", () => {
dialogEl.showModal();
});
yesBtn.addEventListener("click", () => {
// Below line can be replaced by your DB query
result.textContent = "This could have been your DB query";
dialogEl.close();
});
noBtn.addEventListener("click", () => {
result.textContent = "";
dialogEl.close();
});
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
body {
font-family: "Roboto";
}
button {
background: hsl(206deg 64% 51%);
color: white;
padding: 0.5em 1em;
border: 0 none;
cursor: pointer;
}
dialog {
border: 0 none;
}
.result {
margin-top: 1em;
}
<dialog>
<button class="yes">Yes</button>
<button class="no">No</button>
</dialog>
<button class="open-dialog">Click me</button>
<div class="result"></div>
Can I use?
Right now the compatibility is great with all the modern browsers.
I'm currently working on a web workflow which already has it's own notifications/dialog boxes, and I recently (like, today) created a tiny, custom (and tailored to the project needs) YES/NO dialog box.
All dialog boxes appeard over a modal layer. Full user attention is required.
I define the options configurations in this way. This options are used to define the buttons text, and the values associated to each button when there clicked:
optionsConfig = [
{ text: 'Yes', value: true },
{ text: 'No', value: false }
]
The use of the function goes something like this:
const answer = await notifier.showDialog('choose an option', options.config);
if (answer) {
// 'Yes' was clicked
} else {
// 'No' was clicked!
}
What I do, it's simply creating a async event handler for each option, it means, there is a simple handler assigned to each button. Each handler returns the value of the option. The handlers are pushed inside an array.
The array is then passed to Promise.race, and that is the return value of the showDialog method, which will correspond to the value's actual value (the one returned by the handler).
Can't provide too much code. As I said it's a very specific case, but the idea may be usefull for other implementations. Twenty lines of code or so.
A vanilla JavaScript option with a class for creating the custom modal dialog which includes a text box:
jsfiddle:
https://jsfiddle.net/craigdude/uh82mjtb/2/
html:
<!DOCTYPE html>
<html>
<style>
.modal_dialog
{
box-sizing: border-box;
background-color: #ededed;
border-radius: 5px;
border: 0.5px solid #ccc;
font-family: sans-serif;
left: 30%;
margin-left: -50px;
padding: 15px 10px 10px 5px;
position: fixed;
text-align: center;
width: 320px;
}
</style>
<script src="./CustomModalDialog.js"></script>
<script>
var gCustomModalDialog = null;
/** this could be static html from the page in an "invisible" state */
function generateDynamicCustomDialogHtml(){
var html = "";
html += '<div id="custom_modal_dialog" class="modal_dialog">';
html += 'Name: <input id="name" placeholder="Name"></input><br><br>';
html += '<button id="okay_button">OK</button>';
html += '<button id="cancel_button">Cancel</button>';
html += '</div>';
return html;
}
function onModalDialogOkayPressed(event) {
var name = document.getElementById("name");
alert("Name entered: "+name.value);
}
function onModalDialogCancelPressed(event) {
gCustomModalDialog.hide();
}
function setupCustomModalDialog() {
var html = generateDynamicCustomDialogHtml();
gCustomModalDialog = new CustomModalDialog(html, "okay_button", "cancel_button",
"modal_position", onModalDialogOkayPressed, onModalDialogCancelPressed);
}
function showCustomModalDialog() {
if (! gCustomModalDialog) {
setupCustomModalDialog();
}
gCustomModalDialog.show();
gCustomModalDialog.setFocus("name");
}
</script>
<body>
<button onclick="showCustomModalDialog(this)">Show Dialog</button><br>
Some content
<div id="modal_position">
</div>
Some additional content
</body>
</html>
CustomModalDialog.js:
/** Encapsulates a custom modal dialog in pure JS
*/
class CustomModalDialog {
/**
* Constructs the modal content
* #param htmlContent - content of the HTML dialog to show
* #param okayControlElementId - elementId of the okay button, image or control
* #param cancelControlElementId - elementId of the cancel button, image or control
* #param insertionElementId - elementId of the <div> or whatever tag to
* insert the html at within the document
* #param callbackOnOkay - method to invoke when the okay button or control is clicked.
* #param callbackOnCancel - method to invoke when the cancel button or control is clicked.
* #param callbackTag (optional) - to allow object to be passed to the callbackOnOkay
* or callbackOnCancel methods when they're invoked.
*/
constructor(htmlContent, okayControlElementId, cancelControlElementId, insertionElementId,
callbackOnOkay, callbackOnCancel, callbackTag) {
this.htmlContent = htmlContent;
this.okayControlElementId = okayControlElementId;
this.cancelControlElementId = cancelControlElementId;
this.insertionElementId = insertionElementId;
this.callbackOnOkay = callbackOnOkay;
this.callbackOnCancel = callbackOnCancel;
this.callbackTag = callbackTag;
}
/** shows the custom modal dialog */
show() {
// must insert the HTML into the page before searching for ok/cancel buttons
var insertPoint = document.getElementById(this.insertionElementId);
insertPoint.innerHTML = this.htmlContent;
var okayControl = document.getElementById(this.okayControlElementId);
var cancelControl = document.getElementById(this.cancelControlElementId);
okayControl.addEventListener('click', event => {
this.callbackOnOkay(event, insertPoint, this.callbackTag);
});
cancelControl.addEventListener('click', event => {
this.callbackOnCancel(event, insertPoint, this.callbackTag);
});
} // end: method
/** hide the custom modal dialog */
hide() {
var insertPoint = document.getElementById(this.insertionElementId);
var okayControl = document.getElementById(this.okayControlElementId);
var cancelControl = document.getElementById(this.cancelControlElementId);
insertPoint.innerHTML = "";
okayControl.removeEventListener('click',
this.callbackOnOkay,
false
);
cancelControl.removeEventListener('click',
this.callbackOnCancel,
false
);
} // end: method
/** sets the focus to given element id
*/
setFocus(elementId) {
var focusElement = document.getElementById(elementId);
focusElement.focus();
if (typeof focusElementstr === "HTMLInputElement")
focusElement.select();
}
} // end: class
The easiest way to ask before action on click is following
<a onclick="return askyesno('Delete this record?');" href="example.php?act=del&del_cs_id=<?php echo $oid; ?>">
<button class="btn btn-md btn-danger">Delete </button>
</a>
document.getElementById("button").addEventListener("click", function(e) {
var cevap = window.confirm("Satın almak istediğinizden emin misiniz?");
if (cevap) {
location.href='Http://www.evdenevenakliyat.net.tr';
}
});
Related
I have the following code that hides a div when there is anything typed in a textbox.
<script type="text/javascript" charset="utf-8">
$('#email').change(function () {
var len = $('#email').val().length;
if (len > 0) {
$("#user_accounts").fadeOut(1)
} else {
$("#user_accounts").fadeIn(1)
}
});
</script>
This is working but it only works after you click away from the textbox and not when you start typing. I wanted to see if there is a way to execute this code when you start typing and not just when there is text in the field and you click away.
It's quite easy, here's the code:
document.getElementById('myInput').addEventListener('keyup', () => {
if (document.getElementById('myInput').value.length > 0) {
document.getElementById('myDiv').style.display = 'none';
} else {
document.getElementById('myDiv').style.display = 'block';
}
})
#myInput {
width: 200px;
height: 35px;
padding: 0 10px;
background: #333;
color: #fff;
border: 0;
outline: 0;
font-family: arial;
}
#myInput::placeholder {
color: #ccc;
}
#myDiv {
width: 220px;
height: 70px;
margin-top: 20px;
line-height: 70px;
text-align: center;
font-family: arial;
background: red;
color: #fff;
}
<html>
<body>
<input id='myInput' type="text" placeholder="Type here!">
<div id='myDiv'>Can you see me?</div>
</body>
</html>
Basically using
document.getElementById('myInput').addEventListener('keyup', () => { // your function }
you're calling a function everytime someone types inside the input (actually the function is called only when you realese a key)
and then you just check for the input's value length inside of the function and hide or not the div based on the length.
Hope It's what you're looking for, if you have any question let me know.
According to the documentation, for <input type="text">, the change event only triggers after the element loses its focus (e.g. clicking away).
Unlike change event, input event is fired every time the value of the element changes. Therefore, it fits better to your usecase.
Your code will look like this:
$('#email').on('input', function() {
var len = $('#email').val().length;
if (len > 0) {
$("#user_accounts").fadeOut(1)
} else {
$("#user_accounts").fadeIn(1)
}
});
for cleaner code, I would recommend using inline HTML and instead of onchange, I would actually use onkeyup (as other commentators noted) this event would call a named function which would be binded to the event.
as follows:
HTML
<element onkeyup="handleInputKeyup">...</element>
JS
const handleInputKeyup = (event) => {//do something with the event here};
My aim is for the users to click the button multiple times and on each click it changes the color and the wording on the button. I got the word and the color to change on the first and second click but it doesn't change when I click again. What am I doing wrong?
You can find my code below:
$(document).ready(function() {
$("button").click(function() {
$("#partyButton").text("Party Over!");
$(this).addClass("click").one("click", function() {
$("#partyButton").text("Party Time!");
$(this).removeClass();
});
});
});
button {
color: white;
font-family: 'Bungee';
background-color: #222;
border: none;
border-radius: 5px;
width: 25%;
padding: 20px;
cursor: pointer;
}
.click {
background-color: #0A8DAB;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="partyButton" type="button"> party time!</button>
You can achieve this By using toggleClass and check with .hasClass()
//button
$(document).ready(function (){
$("button").click(function (){
$(this).toggleClass("click").text($(this).hasClass('click') ? "Party Time":"Party Over!");
});
});
button{
color: white;
font-family: 'Bungee';
background-color:#222;
border: none;
border-radius: 5px;
width: 25%;
padding: 20px;
cursor: pointer;
}
.click{
background-color:#0A8DAB;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id = "partyButton" type = "button"> party time!</button>
Code Explanation:
$(this).toggleClass("click") this will toggle between class on each click
$(this).hasClass('click') check if this element has a class it return true/false .. you can also use it like if($(this).hasClass('click')){}else{}
() ? : ; shorthand if statment
Also Take care when you use removeClass() without assign any class it will remove all the classes for this element
The problem is you are registering an one time click event for the button while the button is clicked for the first time, which will detach the event once clicked. This is the reason you are not getting the event further. It is unnecessary and confusing
You just need the below implementation
$("#partyButton").click(function(){
if($(this).hasClass('click'))//check whether it party time or not
{
$(this).text("Party Time!").toggleClass('click');
}
else
{
$(this).text("Party Over!").toggleClass('click');
}
})
https://jsfiddle.net/n5hdg7tv/
For example:
$(function() {
$('#partyButton').on('click', function () {
var $button = $(this);
if($button.hasClass('click')) {
$button.removeClass('click').text('Party Time !');
} else {
$button.addClass('click').text('Party Over !');
}
})
});
I would like to develop a popup function (html,css,js) and use it anywhere in the webpage.
Here is the pop function:
function pop (options) {
var mod = function( options ) {
var that = this;
this.op = { title: 'new pop' }; // for startup
for( var option in options ){
this.op[ option ] = options[ option ];
};
this.title = options.title;
this.build();
this.remove = function() { // remove this pop
document.body.removeChild( that.cover );
};
};
mod.prototype.build = function() { // create new pop
this.cover = document.createElement('div');
document.body.appendChild( this.cover );
};
return new mod( options );
}; // pop
var callpop = pop( { title: 'make a pop' } ); // so i can call
callpop.remove(); // and remove it
First question, is this design pattern make sense?
Second question, can i do :
this.remove = function() { // remove this pop
document.body.removeChild( that.cover );
that = undefined; // add this line to make the callpop undefined
};
console.log( callpop ); // so i can check if pop is display, than i can remove it by callpop.remove(), and make a new one callpop = pop()
beside give me a link, can u give me some short example please? Many thank!
Update 1:
I just would like to know, if you get a job to write a popups function, how would you code it? is my example make sense?
Since you are driving the whole popup flow with javascript thus it would be hard to make modifications on markup side. It's better to keep html in either markup or templates. Because it's easier to make edits in markup for the display part.
One very nice example of this would be how bootstrap manages its modal popups. Have a look at here. They drive it completely by markup and events are attached at the time of page load.
You can customize this behavior as per your needs but try to keep javascript in .js and html in .html or .templates.
Also, have a look at their source code for modal.
And for using template for modal you should have look at how angular-ui-bootstrap handles those scenarios.
Update:
For a basic reference see this demo in jsbin. And code here.
<SCRIPT TYPE="text/javascript">
function popup(mylink, windowname)
{
if (!window.focus)
return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else href=mylink.href;
window.open(href, windowname, 'width=400,height=200,scrollbars=yes');
return false;
}
</SCRIPT>
popup('autopopup.html', 'ad')
Hi you can use this popup. Below the complete example of custom design
popup.
$(document).ready(function() {
// When site loaded, load the Popupbox First
loadPopupBox();
$('#popupBoxClose').click(function() {
unloadPopupBox();
});
$('#container').click(function() {
unloadPopupBox();
});
});
function unloadPopupBox() {
// TO Unload the Popupbox
$('#popup_box').fadeOut("slow");
$("#container").css({
// this is just for style
"opacity": "1"
});
}
function loadPopupBox() {
// To Load the Popupbox
$('#popup_box').fadeIn("slow");
$("#container").css({
// this is just for style
"opacity": "0.3"
});
return false;
}
/* popup_box DIV-Styles*/
#popup_box {
display: none;
/* Hide the DIV */
position: fixed;
_position: absolute;
/* hack for internet explorer 6 */
height: auto;
width: auto;
background: #FFFFFF;
top: 150px;
z-index: 100;
/* Layering ( on-top of others), if you have lots of layers: I just maximized, you can change it yourself */
margin-left: 15px;
/* additional features, can be omitted */
border: 2px solid #ff0000;
padding: 15px;
font-size: 15px;
-moz-box-shadow: 0 0 5px #ff0000;
-webkit-box-shadow: 0 0 5px #ff0000;
box-shadow: 0 0 5px #ff0000;
}
#container {
background: #d2d2d2;
/*Sample*/
width: 100%;
height: 100%;
}
a {
cursor: pointer;
text-decoration: none;
}
/* This is for the positioning of the Close Link */
#popupBoxClose {
font-size: 20px;
line-height: 15px;
right: 5px;
top: 5px;
color: #6fa5e2;
font-weight: 500;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- HTML Structure for popup box-->
<div id="popup_box">
<!-- OUR PopupBox DIV-->
<h1>This IS A Cool PopUp</h1>
<div runat="server" id="dvContent"></div>
<a id="popupBoxClose">Close</a>
</div>
<!-- Main Page -->
<div id="container">
<h1>Click on link to load sample popup</h1>
<input type="button" value="Click Me" id="btnClick" onclick="loadPopupBox();" />
</div>
I have a page with a link to a form. After clicking the link the form shows up and the link disappears. The problem that i have is, when i click the browser's back button, the values of the URL is changed, but the state of the page doesn't go back to previous state. The form should disappear and the link shows back. Also on reload when the form is visible, the page goes back to its first state, which i need to prevent from happening.
Code :
<html>
<style>
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
</style>
<body>
<div id="categContainer1">
<div class="titimmo">Real Estate</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made"/>
<h4>Price :</h4>
<input type="text" name="modele"/><br/><br/>
</form>
</div>
<script>
function stepone() {
document.getElementById('a_categ').onclick = function () {
document.getElementById('categContainer1').className += " hidden";
document.getElementById('formContainer').className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
return false
};
}
stepone();
</script>
</body>
</html>
First question is: How to bring back the page to its previous state by clicking the browser's back button?
Second question is: How to prevent the page from going back to its previous state - on reload when it's on second state (when form is visible)?
There are two things you need to do to make it work:
To monitor browser back button click, use
window.onpopstate
method
To remember the form state, you need to store the value in
localStorage or in a cookie.
This is a basic example:
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
<div id="categContainer1">
<div class="titimmo">
Real Estate
</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made" />
<h4>Price :</h4>
<input type="text" name="modele" />
</form>
</div>
Also on Fiddle, where you can actually see how it works.
I'm running into a problem binding both a .blur and .click event handler to the same clickable element. The UX I'm going for is as follows:
a user clicks on the search icon and the search field appears; when a user clicks again on the search icon, they can collapse and hide the search field. If they click away, the search field should hide.
So far, I'm able to achieve most of what I want, except that I can't get the .click binding to toggle the class after it's been clicked. I'm thinking it's possibly because after being toggled the $ selector doesn't have any results to select? I'm relatively new to JavaScript so I'm a little unclear on exactly how JavaScript or jQuery would handle something like this.
Jsfiddle here: http://jsfiddle.net/TpXJe/1/
Edit: including code here so future Stack Overflow users can see it:
html:
<form class="hidden-xs search-container navbar-right search-form" method="get">
<div class="input-group">
<input id="search-box" type="search" class="search-box" name="s" class="search-field form-control" />
<label class="hide">Search for something</label>
<label for="search-box"><span id="searchDivider">|</span>
<div class="icon-continer"> <span class="glyphicon glyphicon-search search-icon"></span>
</div>
</label>
</div>
</form>
css:
.search-container {
right: 0px;
}
#searchDivider {
position: absolute;
right: 0px;
top:31px;
z-index: 1;
color: #brand-success;
cursor: pointer;
font-weight: 200;
}
// Style the search box
$tl: .3s; // transition length
.search-box {
outline-width: 0;
transition: width $tl, border-radius $tl, background $tl;
position: absolute;
right:-37px;
top: 20px;
z-index: 100;
width: 40px;
height: 40px;
border-radius: 20px;
border: none;
cursor: pointer;
background: transparent;
& + label .search-icon {
color: black }
&:hover {
color: white;
background: transparent;
box-shadow: 0 0 0 1px transparent;
& + label .search-icon {
color: white }
}
&.focused {
transition: width $tl cubic-bezier(.18,.57,.25,.94), border-radius $tl;
border: none;
outline: none;
box-shadow: none;
padding-left: 15px;
cursor: text;
width: 600px;
border: 1px solid black;
border-radius: auto;
background: white;
color: black;
& + label .search-icon {
color: black; }
}
&:not(:focus) {
text-indent:-5000px; } // for more-graceful falling back (:not browsers likely support indent)
}
#search-submit {
position: relative;
left: -5000px;
}
.search-icon {
position: absolute;
right: -45px;
top: 14px;
z-index: 1000;
color: black;
cursor: pointer;
width: 60px;
height: 60px;
padding: 23px;
}
js:
$('.search-icon').click(
function () {
$('.search-box ').toggleClass(' .search-box focused');
});
$('.search-box').blur(
function () {
$('.search-box').removeClass('focused');
});
As Ehsan said in the comments, it appears that clicking the icon while it has already been clicked once fires both click() and blur() events. I just added in a variable to represent the state of clicked/unclicked and it works for me! Also in the updated fiddle below is what I believe you intended to do that Jacob mentioned in the comments-the class name is 'focused' not '.search-box focused'.
Updated JSFiddle Link
Here is the JS Code:
var clicked = false;
$('.search-icon').click(
function () {
if (clicked) {
$('.search-box ').removeClass('focused');
clicked = false;
} else {
$('.search-box ').addClass('focused');
clicked = true;
}
});
$('.search-box').blur(
function () {
$('.search-box').removeClass('focused');
What I have stated to do recently is set up all my event listeners as a variable (object). It makes being able to assign multiple events to a single object very easy.
/**
* Event listeners.
* Params: element, event : method
* NOTE: element is passed in as a string, not jQuery object!
* This so we have the possibility of multiple events for a single element (eg. focus & change for the same element).
*
*/
eventHandlers: {
'a click': 'onAnchorClick',
'a hover': 'onAnchorHover'
},
/**
* Registers all event listeners/handlers.
* #returns {void}
*
*/
registerEventHandlers: function() {
var that = this;
$.each(this.eventHandlers, function(key, val) {
var split = key.split(" ");
var element = split[0];
var event = split[1];
$(document).on(event, element, that[val]);
});
}
...
/**
* Event listener for all anchor click events.
* #param {object} event | The click event.
* #returns {void}
*
*/
onAnchorClick: function(event) {
console.log('click event');
// For example purposes:
var ga_eventData = {
'category': 'Text Link',
'action': 'Click',
'label': event.currentTarget.innerText,
'optionalData': {
'page': window.location.protocol + '//' + window.location.host + window.location.pathname
}
}
GA.registerEvent(ga_eventData); // GA is my google analytics module in this example
},
/**
* Event listener for all anchor hover events.
* #param {object} event | The hover event.
* #returns {void}
*
*/
onAnchorHover: function(event) {
console.log('hover event');
}
...
Then in my initialization method, I simply call:
/**
* Initialization method.
* #returns {void}
*
*/
initialize: function() {
var that = this;
that.registerEventHandlers();
}