fail to focus on page load - javascript

I can focus on the text input when I click the button but it doesn't focus on the text input when page first loaded even though I am using the same function. How can I focus at the input textfield once the page is loaded ?
http://codepen.io/anon/pen/derwi
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
function generate_question (){
var num1 = Math.floor(Math.random()*10),
num2 = Math.floor(Math.random()*10);
$('.result').hide();
$('.left').html(num1 + ' x ' + num2 + ' = <input type="text" size="3" class="answer">');
$('.answer').val('');
$('.answer').focus();
$('.answer').keypress(function(e){
if (e.which == 13) {
if ($(this).val() == num1 * num2) {
$('.result').html('Very Good!');
$('.result').show();
} else {
$('.result').html('Try Again');
$('.result').show();
}
}
})
}
$(document).ready(function(){
generate_question();
$('#again').click(function(){
generate_question();
});
$('#again').keypress(function(e){
if (e.which == 32){
generate_question();
}
});
})
</script>
</head>
<body>
<div class="content">
<div class="left"></div>
<div class="result"></div>
</div>
<div class="instruction">
Hit enter to check your answer.
<button type='button' id='again' style='margin-top: 10px;'>Do another one?</button>
</div>
</body>
</html>

Try $('.answer').focus(); in your ready function
$( document ).ready(function(){
$('.answer').focus();
});
DEMO: http://plnkr.co/edit/EX0xS9d8o3TqUqiEOAL5?p=preview

Related

Count key presses and display them in HTML

I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>

Can't add 1 by pressing button

I made a simple HTML with JS inside, and its about add 1 to variable and keep running until user gets 1 by rng(random number generator). Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
function clicked(){
var num = Math.floor((Math.random() * 100) + 1);
var click = 0;
click = click+1;
if(num == 1){
document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
document.getElementById("press").disabled = true;
}
else{
document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
}
}
</script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
<input type="button" value="Press Me!" id="press" onclick="clicked()">
<div id="print"></div>
</body>
</html>
At this code, click = click+1 don't work and click is stuck at 1. What should I do?
The reason your click stuck to 1 is whenever function called you are declaring
click = 0, so it is initialized every time you press the button. So just declare var click outside of function clicked() and see the magic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
var click = 0;
function clicked(){
var num = Math.floor((Math.random() * 100) + 1);
click = click+1;
if(num == 1){
document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
document.getElementById("press").disabled = true;
}
else{
document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
}
}
</script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
<input type="button" value="Press Me!" id="press" onclick="clicked()">
<div id="print"></div>
</body>
</html>

jQuery Custom Scrollbar doesn't scroll bottom well

I am creating a chat service, everything works fine except for one little detail, the scrollbar. I'm using the jQuery Custom Scrollbar plugin.
It doesn't go to the bottom, sometimes it's does really well but sometimes it stuck in the half from the last message, I have been working in this detail for one week and I can't figure out what's the problem yet.
Here's my HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<title>---</title>
<!-- Main CSS -->
<link rel="stylesheet" href="css/default.css">
<!-- Extra CSS -->
<link href="css/jquery.mCustomScrollbar.css" rel="stylesheet"/>
<!-- All JS Scripts-->
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.mCustomScrollbar.min.js"></script>
<script type="text/javascript" src="js/jquery.elastic.source.js"></script>
<script type="text/javascript" src="js/jquery.xdomainrequest.min.js"></script>
<script type="text/javascript" src="js/flowtype.js"></script>
<script type="text/javascript" src="js/cpg_smartphones_proto.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<!-- Perfect Scrollbar
<link href="css/perfect-scrollbar.css" rel="stylesheet">
<script src="js/perfect-scrollbar.js"></script>-->
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css/ie.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="css/ie8.css" />
<![endif]-->
<!--[if !IE]><!--><script>
if (/*#cc_on!#*/false) {
document.documentElement.className+=' ie10';
}
</script><!--<![endif]-->
</head>
<body onload="initialize()">
<div class="row">
<div id="chat_intro">
<div class="chat_caller" onclick="goToChat()">
<h1>Enter</h1>
</div>
</div>
</div>
<div id="chat_box">
<div id="chat_top" hidden="hidden">
<div id="chat_header">
<h4>Personal support</h4>
<p>Find the best product for you.</p>
</div>
<div id="chat_avatar"></div>
</div>
<div id="chat_container">
<div id="history_div">
<div id="history_mc">
</div>
</div>
</div>
<div id="chat_footer">
<textarea id="input_area" type="text" onkeypress="chatHandler(event)">
</textarea>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#chat_box').hide();
$('#chat_footer').hide();
});
</script>
</script>-->
</body>
</html>
And now, the JS:
function goToChat() {
origin = BANNER_NAME + "_" + uid + metaData;
$("#chat_intro").hide();
$("#chat_box").show();
$("#chat_top").show();
$("#chat_container").show();
$("#chat_footer").show();
$("#history_div").mCustomScrollbar( {
theme : "dark-thick",
advanced : {
updateOnContentResize : true
}
});
document.getElementById('input_area').focus();
chat();
}
function chatHandler(event) {
// ENTER key
var key;
if (window.event) // IE8 and earlier
{
key = event.keyCode;
} else if (event.which) // IE9/Firefox/Chrome/Opera/Safari
{
key = event.which;
}
InputInterface.restartTimeout();
if (key == 13) {
chat();
$('#input_area').focus();
event.keyCode = 0;
}
}
function chat() {
// Build request
var chatText = "";
if (!initialized) {
chatText = "hi";
}
else {
chatText = input_area.value;
if(chatText.trim()=="")return;
var userAnswer = USER + input_area.value + TIME + getTimeStamp() + TIME_END + FONT_END;
history_mc.innerHTML += userAnswer;
$("#history_div").mCustomScrollbar("update");
setTimeout(function(){
$("#history_div").mCustomScrollbar("scrollTo", "bottom");
});
$(input_area).val("");
if(getUrlParameter("isMobile") == "true") hideKeyboard();
}
$("#deleteThis").remove();
InputInterface.prepareSending(chatText);
setTimeout(function(){history_mc.innerHTML += TYPING_MESSAGE;
$("#history_div").mCustomScrollbar("scrollTo", "bottom");});
if(!initialized){
InputInterface.flush();
initialized = true;
}
}
//Start calling recursively getMsgId until the retries max out or succesfully get an Id
function getResponse(json) {
start = new Date().getTime();
processRetries = 0;
responseRetries = 0;
getMessageId(json);
}
function displayResponse(response) {
$("#deleteThis").remove();
history_mc.innerHTML += BM_INI+ response_number +BM_FIN + response + TIME + getTimeStamp() + TIME_END + FONT_END;
$("#history_div").mCustomScrollbar("update");
setTimeout(function(){
if (DEBUG) console.log("#conv"+response_number);
$("#history_div").mCustomScrollbar("scrollTo", "#conv"+response_number);
response_number++;
},250);
document.getElementById('input_area').focus();
}
I hope you can shine me with you jedi powers, thank you so much.
Greetings.

textbox style following jquery mobile

i having problem in creating textbox using jquery that is implemented in webview. here is the code
<html>
<head>
<title>jQuery Mobile List Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>
<script type="text/javascript">
var counter = 1;
$('#AddQuestion').live('pagecreate', function() {
$('#button').click(function() {
$('#TextBoxesGroup').append("<input type ='text' id='option" + counter + "' placeholder='option" + counter + "'>");
$('#TextBoxesGroup').textinput();
if (counter > 4) {
document.getElementById("button").style.display = 'none';
}
counter++;
});
});
</script>
</head>
<body>
<div data-role="page" id="AddQuestion">
<div data-role="header" data-position="fixed">
<h1>AddQuestion</h1>
</div>
<div data-role="content">
<form name="newdocument">
<div data-role="listview" id="TextBoxesGroup"></div>
<input type="button" value="Add Option" id="button">
</form>
</div>
</div>
</body>
</html>
i have tried this code in jsfiddle and when i press the add option button it shows unstyle textbox. what would be the problem?
You need to trigger create on the page to have jQuery mobile apply the additional markup and classes required for styling.
<script type="text/javascript">
var counter = 1;
$('#AddQuestion').live('pagecreate', function() {
$('#button').click(function() {
$('#TextBoxesGroup').append("<input type ='text' id='option" + counter + "' placeholder='option" + counter + "'>");
$('#TextBoxesGroup').textinput();
if (counter > 4) {
document.getElementById("button").style.display = 'none';
}
$('#AddQuestion').trigger('create');
counter++;
});
});
</script>

How to prevent empty input in text input form?

Here is my HTML -
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> My Shopping List</title>
<link rel="stylesheet" type="text/css" href="shoppinglist.css">
<link href='http://fonts.googleapis.com/css?family=Quicksand:300,400|Advent+Pro:300' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="shoppinglist.js"></script>
</head>
<body>
<div class="container">
<p id="shoppinglist"> My Shopping List App</p>
<input type="text" name="user" class="entertext">
<input type="button" value="Enter" class="returnkey">
<br>
<br>
<ol></ol>
</div>
</body>
</html>
Here is my JavaScript -
$(document).ready(function () {
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$("input[type='text']").keyup(function(event) {
if(event.keyCode == 13) {
$("input[type='button']").click();
}
});
$("ol").on("click", "input[type='checkbox']", function() {
$(this).parent().remove();
});
});
How do I create JavaScript for someone whose entering empty? So something to prevent them from empty text input?
You can check if the value of the text input is equal to a blank string:
$("input[type='button']").on("click", function() {
var item = $("input[type='text']").val();
//start new code
if ($.trim(item) === '') {
alert("Please Enter Something!");
return false;
}
//end new code
$("ol").append("<li style='display:none;'>"+ item+"<input type='checkbox'></li><br />");
$("li:last").show("clip");
});
$.trim() removes any extra white-space, to make sure the input doesn't just have white-space as a value.
Something like this?
$('.returnkey').on('click', function() {
var string = $.trim($('.entertext').val());
if (string == '') {
alert('Field is empty');
return false;
}
}

Categories