Disappear the alert box with time based - javascript

I want to disappear the alert box after a certain amount of time. I have heard that this is impossible in Javascript, so is there another way of making this happen?

Try this jsbin code - A custom alert box for you
http://jsbin.com/ibUrIxu/1/edit
or Try this on your .html file
Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function customAlert(msg,duration)
{
var styler = document.createElement("div");
styler.setAttribute("style","border: solid 5px Red;width:auto;height:auto;top:50%;left:40%;background-color:#444;color:Silver");
styler.innerHTML = "<h1>"+msg+"</h1>";
setTimeout(function()
{
styler.parentNode.removeChild(styler);
},duration);
document.body.appendChild(styler);
}
function caller()
{
customAlert("This custom alert box will be closed in 2 seconds","2000");
}
</script>
</head>
<body onload="caller()">
</body>
</html>

Working Demo -- Here is a custom alert box and function what you need
function cancelDiv() {
$("#div1").hide();
}
function ShowDiv() {
$("#div1").css("backgroundColor", "white");
$("#div1").show();
setTimeout(function(){$("#div1").hide()}, 3000)
}
$(function () {
$("#div1").hide();
$("#div1").draggable();
});

You can do this by using a custom alert message. One example of a notification framework is ToastR. You can also create your own message framework.
You cannot dismiss a regular JavaScript alert box though.

Related

Show or hide a div depending on a radiobutton (checked/not)

After a long time here and using all your information and comments, I was able to solve all of my code problems. Actually, I don't speak too much English. Sorry for that. Anyway, here we go!
I'm doing business practices and they gave me a project and I've almost finished it, but I cannot deal with it:
I have to detect the OS user system by JS and then after that, if the client is using Windows, I should advise him that he can install a ".exe" to run this app via desktop displaying just a div within a description (here is the div — just a rectangle in this case, so, it doesn't matter). After trying for all of this afternoon, I couldn't solve it and I decided to still testing in at home:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>radio button test [FAILED haha]</title>
<link rel="stylesheet" href="index.css">
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{document.getElementById("bad").checked = true;}
});
if($(#good).is(":checked")){
$(#ident).style.display = "block";
};
</script>
</head>
<body>
<center>
<div id="ident"></div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
</center>
</body>
</html>
The problem: I tried to use jQuery to use the Change event on input#windows. The problem is, if it's the default option, the div won't appear, and, if i try it inside out.
I'm done T.T
In advance, thanks.
PS: it's my first post, so if I did something wrong, sorry!
Your problem is that you are not listening to the changeevent. You will have to do that, and when the change event is fired, decide what to do based on the checked/unchecked status of the radio buttons. Also, since you mention that listening to change event doesn't do anything to the radio buttons on page load, that is because you are not evaluating the checked/unchecked status on page load.
p/s: And you forgot to wrap your selector in quotes.
Therefore, the solution is to fire a function on both page load (or DOM ready) and upon change:
$(document).ready(function() {
var systemName = navigator.platform;
if (systemName.indexOf('Win') != -1) {
$('#good').prop('checked', true);
} else {
$('#bad').prop('checked', true);
}
var updateIdent = function() {
if ($('#good').is(":checked")) {
$('#ident').show();
} else {
$('#ident').hide();
}
}
// Update when change event is fired
$('form input[type="radio"]').on('change', updateIdent);
// Update upon DOM ready
updateIdent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ident">IDENT</div>
<form action="">
<input type="radio" name="system" id="good" value="good">Windows
<br>
<input type="radio" name="system" id="bad" value="bad">others
</form>
Your markup is fine, you're just missing some quotes in your jquery and having problems setting the display: block; This JS will fix it:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
document.getElementById("good").checked = true;
}else{
$document.getElementById("bad").checked = true;
}
});
if($('#good').is(":checked")){
$('#ident').css('display','block');
};
However, unless you specifically need the radio buttons, you can do without them entirely. Some JS like this will work best:
$(document).ready(function(){
systemName = navigator.platform;
if(systemName.indexOf('Win') != -1){
$('#ident').css('display','block');
}else{
$('#ident').css('display','none');
}
});
Hope that helps!
Try this:
$('.radioBtn').change(function () {
if (this.value == 'good') {
$('#ident').show();
} else if (this.value == 'bad') {
$('#ident').hide();
}
});
systemName = navigator.platform;
if (systemName.indexOf('Win') > -1) {
$('#good').prop("checked", true).change();
} else {
$("#bad").prop("checked", true).change();
}
See it in action: https://jsfiddle.net/fmotankv/24/
Also, note that my Fiddle uses CSS to automatically hide the #ident div. I would recommend this method to avoid non-Windows users from potentially seeing the div flash on their screen before being removed by the code.

Chrome drag drop file/folder not working

I am trying to create PoC for Drag and drop a folder onto Chrome (v46) with the below code but alert is not getting triggered. Chrome switches to the folder browser view when a folder is dropped or opens the dragged file as it is dropped. Basically it keeps the default behavior. I tried to open the html file like "http://localhost/index.html" and "file:///C:\index.html" but both behave the same.
Where am I going wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Drop File/Folder</title>
</head>
<body>
<div id="dropzone" style="border: solid 1px; padding: 200px;">Drop files or folders here</div>
<script type="text/javascript">
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function (e) {
alert("dropped!");
e.preventDefault();
};
// I also tried this but no success
//dropzone.addEventListener('drop', function (e) {
// alert("dropped!");
// e.preventDefault();
//});
</script>
</body>
</html>
It turns out you need to add a dragover handler.
dropzone.ondragover = function (e) {
e.preventDefault();
};

Why is my javascript function not being invoked for simple MVC tutorial? Why can't I debug either?

Problem
I have been following this simple tutorial found here. However, I want to modify it so that the calculator is only invoked when the client clicks submit. However, when I click the submit button, no action is observed. I am not even seeing the alert.
EDIT:
I have modified the code per Ojay's suggestions. However, I am getting this error when I try to debug. I am getting this exact issue except I have VS13 Update 3. Multiple things going on here?
Code
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample Calculator</title>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#my-calc').on('submit', function () {
alert("This button is working?");
calculate();
});
function calculate()
{
alert('hi');
//Add
try {
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
} catch (e) {
}
//Subtract
try {
$('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));
} catch (e) {
}
//Multiply
try {
$('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));
} catch (e) {
}
//Divide
try {
$('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));
} catch (e) {
}
}
});
</script>
</head>
<body>
<div><h4>Sample Calculator</h4></div>
#using (Html.BeginForm())
{
<p> #Html.Label("Input 1") : #Html.TextBox("num1","0")</p>
<p> #Html.Label("Input 2") : #Html.TextBox("num2", "0")</p>
<p> #Html.Label("Sum ") : #Html.TextBox("sum")</p>
<p> #Html.Label("Sub ") : #Html.TextBox("sub")</p>
<p> #Html.Label("Mult ") : #Html.TextBox("mul")</p>
<p> #Html.Label("Div ") : #Html.TextBox("div")</p>
<button id="my-calc" type="button">Calculate</button>
}
</body>
</html>
Attempts
Put in alert. Not observed.
Rewrote it from documents.on.ready(). See below.
RTFM as seen here
Searched stackoverflow. Didn't find anything that worked.
Edit: I had something originally like the tutorial I was looking at. I had:
$(document).ready(function(){
$('#my-calc').on('submit', function (){ //stuff}
}
I don't understand why my function is not being invoked? My form id is correct. All I want to do is invoke this calculator method so my label's sum, sub, mult, and div display the results.
Please pardon the simplistic nature of this question, but I feel it would be useful for others doing .NET MVC tutorials who might also be having this problem. As a result of this question,
I decided to obtain a book on jQuery. Thanks for your assistance.
You're running your code before your form is rendered. Therefore, $('.my-calc') is returning an empty object, and doing nothing. Also, the selector for an item by ID is $('#my-calc'), your selector was looking for an element with class my-calc
// Passing a function into `$()` makes it run after the DOM is ready.
$(function() {
$('#my-calc').on('submit', function (){
alert("This button is working?");
calculate();
});
});
It looks as though there are multiple issues here.
Firstly your selector must be '#my-calc' to correctly select the submit form. Your jQuery code must be wrapped in a document ready handler (as per your added code), or the code needs to appear after the form. Also when you add a submit event handler then you need to return false to stop the form submitting. And lastly (and perhaps the most important), you cannot nest forms. The #using (Html.BeginForm()) creates a form, and then you are creating another one inside it <form id="my-calc">, this is not valid. What the browser will do is just ignore the inner one, so in other words, there will never be a submit event of the my-calc form, becuase the parent form is what is submitted.
Also because you are just doing a calculation on the page with JavaScript, there is no real need for a form anyway, perhaps just a <button type="button" id="my-calc">Calculate</button> would be better with a click event.
Now your calculate function also has errors
every calculation line is missing a $ in the attempt to get the num1 value
so
$('#sum').val((parseInt(('#num1').val())) + parseInt($('#num2').val()));
should be
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
and there is an additional issue with the multiplication one, the input is not #mult its #mul as per your #Html.TextBox("mul").
So all of that together, something like the following should resolve your issues
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample Calculator</title>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#my-calc').on('click', function () {
calculate();
});
function calculate() {
//Add
try {
$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));
} catch (e) {
}
//Subtract
try {
$('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));
} catch (e) {
}
//Multiply
try {
$('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));
} catch (e) {
}
//Divide
try {
$('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));
} catch (e) {
}
}
});
</script>
</head>
<body>
<div><h4>Sample Calculator</h4></div>
<p> #Html.Label("Input 1") : #Html.TextBox("num1", "0")</p>
<p> #Html.Label("Input 2") : #Html.TextBox("num2", "0")</p>
<p> #Html.Label("Sum ") : #Html.TextBox("sum")</p>
<p> #Html.Label("Sub ") : #Html.TextBox("sub")</p>
<p> #Html.Label("Mult ") : #Html.TextBox("mul")</p>
<p> #Html.Label("Div ") : #Html.TextBox("div")</p>
<button id="my-calc" type="button">Calculate</button>
</body>
</html>
For ids in jquery, you have to use #my-calc
But frankly, I think you're looking to call calculate on the button click otherwise you're going to have to submit your form every time you press the button, which kinda defeats the purpose of the javascript.
$("input").on("click", calculate);
http://jsfiddle.net/4pwakehm/
Your code isn't working because you don't have # in your Javascript.
# should be in front of the name, to represent an Id.
The . should be in front of the name, to represent an class.
You could is essentially do:
$(document).ready(function () {
$("#my-calc").on("click", function () {
alert("Triggered alert for click.");
});
});
Keep in mind that with $(document).ready utilizes jQuery.
That is an example, you should also use your console in the browser to help debug Javascript. Which will help troubleshoot such issues.

Simple&Basic JS - 1st attempt to javascript (want it jQuery free)

First attempt to javascript.. not sure what I'm doing wrong...
Trying to clear the "Sample Here" when i hover mouse or focus, or click.
And Alert when the button is clicked..
I'd rather advices how I can avoid using functions inside the HTML and use them
under the to separate js/html completely!
<!DOCTYPE html>
<html>
<head>
<title>Java Script Practicing</title>
</style>
<script>
document.onreadystatechange = function ()
{
if (document.readyState == "complete")
{
//Page Loaded
function go()
{
alert("done");
}
function clear()
{
var x = document.getElementById("x").value;
x = "";
}
}
}
</script>
</head>
<body>
<form method="post">
<input onclick="clear();" type="text" id="x" value="Sample here" />
<button onclick="go();">Click !</button>
</form>
</body>
</html>
HTML5 documents don't require you state type for a <script> element if it's javascript, and you want to state which character set your document is going to use. This is pretty much always going to be utf8.
That said, you want to tap into the DOMContentLoaded event:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Java Script Practicing</title>
</head>
<body>
<form method="post">
<input class="userinput" type="text" value="Sample here" />
<button class="gobutton">Click !</button>
</form>
<script>
document.addEventListener("DOMContentLoaded", function() {
var button = document.querySelector("button.gobutton");
button.addEventListener("click", function(evt) {
console.log("button was clicked");
}):
var input = document.querySelector("input.userinput");
input.addEventListener("click", function(evt) {
input.value = "";
}):
});
</script>
</body>
</html>
If you want to call your functions from the html as you are doing, you need them to be in the global scope.
Take the definitions for the functions go() and clear() out of the onreadystatechange function. You can still use that function to call the other two, but they must be defined globally.
Also, you cannot simply change the value of the variable x and have that update the element with id=x on the page. Instead, you can use ELEMENT.setAttribute('value', '') to clear the value.
function go() {
alert("done");
}
function clear() {
var x = document.getElementById("x");
x.setAttribute('value', '');
}
document.onreadystatechange = function () {
if (document.readyState == "complete") {
go();
clear();
}
}
Mike has answered your question. Just explaining why your way didn't work. Your functions (go, clear) have become local to the onreadystatechange's callback function's scope. I.e a closure

html body ondblclick get clicked element

so in my html i have this portion:
<body ondblclick="myfunc();">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
and in javascript the function is :
function myfunc() {
do stuff here...
}
i want to know inside myfunc() on which element of the html body the doubleclick was made, because i don't want to triger myfunc() on every doubleclicked element
so how can i detect the id of the element doubleclicked?
<body ondblclick="myfunc(event);">
function myfunc(e) {
// e.target -> element that was clicked
}
make your HTML as
<body ondblclick="myfunc(event);">
and make myfunc as:
function myfunc(event) {
alert(event.target.id); //here you can get element id that is double clicked
event.stopPropagation();
}
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>ondblclick event example</title>
<script>
function initElement() {
var body = document.getElementById("bdy");
body.ondblclick = showAlert;
}
function showAlert(e){
alert(e.target.id);
}
window.onload = initElement;
</script>
</head>
<body id="bdy">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
</html>
you can define different events with use of on or bind suppose..
$("#id").on("doubleClick",function () {} );
so it will know that its double click event..
or for javascript you can use like this
<body ondblclick="myfunc(event);">
function myfunc(event) {
do something..
}

Categories

Resources