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};
I'm trying to change the contents of a div when it's hovered over using JQuery. I've seen answers on stack overflow, but I can't seem to get it working.
I've tried
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
},
function() {
$("tdiv").textContent = 'title';
}
);
I've also replaced "mouseover" with "hover". I've used a variable and the actual div in place of "imgDiv".
This is what my code looks like:
imgDiv = document.getElementById('imgDiv');
tDiv = document.getElementById('titleDiv');
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
}, function() {
$("tdiv").textContent = 'title';
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
You can use jQuery's .hover() function along with the .text() function to do what you want. Also, no need for document.getElementById:
$("#imgDiv").hover(
function() {
$("#titleDiv").text("hovering");
},
function() {
$("#titleDiv").text('title');
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
You can target the div with jQuery, and store it's original value. On mouseout, you can restore it. Also using mouseenter reduces the number of times the logic processes as mouseover will fire for every mouse move over the element.
var $titleDiv = $('#titleDiv');
$("#imgDiv")
.on('mouseenter', function() {
$titleDiv.data('originalText', $titleDiv.text());
$titleDiv.text('hovering');
})
.on('mouseout', function() {
$titleDiv.text($titleDiv.data('originalText'));
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
First of all, replace $("imgDiv") with $("#imgDiv") to get the element with id (#) imgDiv.
Then $("tdiv") doesn't exist, you probably mean $("div") to select a <div>tag in your DOM.
And finally, $("tdiv").textContent doesn't exist. You can try $("div").html() or $("div").text() to get the <div> tag content
--
Quick reminder : jQuery documentation on selectors
$("div") will select the <div> tags
$(".element") will select tags with class="element"
$("#element") will select tags with id="element"
You need to try like this
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
}).mouseleave( function() {
$("#titleDiv").text('title');
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
Easy solution,
var s = document.getElementsByTagName('div');
function out() {
s[0].innerHTML = 'hello';
}
function ibn() {
s[0].innerHTML = 'Myname';
}
<div onmouseout = 'out()' onmouseenter = 'ibn()'> Myname </div>
You cannot call reference a dom with pure Javascript and them manipulate it with jQuery - it will not work.
Try this:
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
});
The titleDiv id has to be referenced in your code using "#", then the id name.
Also, use $("#name_of_id").text("your content") instead of .textContent()
I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>
I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>
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';
}
});