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

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

Related

Ensure JavaScript/jQuery function always runs on page load

I tried all of the alternative examples I could find and couldn't get this to work. I may have it implemented incorrectly. Any help is greatly appreciated.
My issue:
I have a function that is meant to slideDown an alert if specific values in the are in the textarea.
This function works if the user types in the textarea, but the values are usually passed in from another page. How can I make it run without requiring that they interact with the text area?
Here's my example on JSFiddle: Example
And here is the HTML/JS code for easy reading:
HTML
<!doctype html>
<html>
<head>
<title>Alert Test</title>
</head>
<body>
<div class="controls">
<textarea name="q" class="span12" id="textarea" rows="5">one:</textarea>
</div>
Test alert:
<div class="alert alert-error" id="alert" name="alert" style="display: none;">
This is a test alert.
×
</div>
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="textAreaReader.js"></script>
</html>
JS:
$(document).ready(function(){
$('#textarea').on('change keyup paste', function() {
var lines = $('#textarea').val();
var fields = ["one", "two", "three"];
var leng;
for (var i=0; i < fields.length; i++) {
if (lines.indexOf(fields[i] + ':') !== -1){
leng = 1;
}
}
if (leng == 1){
$("#alert").slideDown("fast"); //Slide Down Effect
}else{
$("#alert").slideUp("fast"); //Slide Up Effect
}
});
});
Assigning the function to a variable lets you pass it to the textarea handler and run it on page load.
$(document).ready(function () {
var slide = function () {
…
};
$('#textarea').on('change keyup paste', slide);
setTimeout(slide, 500);
});
Sample.

Disable Function in Javascript event DOM

I have problem with javascript,
in my html code:
<input onclick="myFunction();" />
<script>
function myFunction(){
//excecution of this fucntion
}
</script>
After clicking the input, the function runs. But I want myFunction to be disable after the first click, so when I click again, myFunction won't run.
Just remove the attribute
<input onclick="myFunction(this);" />
<script>
function myFunction(elem){
// code here
elem.removeAttribute('onclick')
}
</script>
or even better use event listeners
<input id="myInput" />
<script>
document.getElementById('myInput').addEventListener('click', myFunction, false);
function myFunction(elem){
// code here
this.removeEventListener('click', myFunction);
}
</script>
One way is to set it to a empty function, after the code has executed.
function myFunction(){
//(..) Some code
myfunction = function(){}; // empty the function so nothing happens next time
}
If you're using jQuery (as You have included it in the tags), I'd go with .one():
<input type="txt" class="my-input" />
function activateClick(){
// single click:
$('.my-input').one('click', function(){
// do stuff ...
});
}
// Activate single click on input element
// Can be reactivated later on, using the same function (see DEMO):
activateClick();
DEMO
Use a boolean indicator to determine whether the function has already run or not. The advantage with this method is that it is easy to reset the function status at a later date.
<!DOCTYPE html>
<html>
<body>
<button onclick='func();'>Function</button>
</body>
<script>
var funcActive=true;
function func() {
if (funcActive) {
funcActive=false;
alert('func ran');
}
}
</script>
</html>

JavaScript focus() function doesn't focus textarea on page load

I have the following code.
<!DOCTYPE html>
<html>
<head>
<title>Focus issue</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var text = document.getElementById('text')
window.onload = function() {
text.focus()
}
window.onhashchange = function() {
text.focus()
}
}//]]>
</script>
</head>
<body>
<textarea id="text"></textarea>
<p>Click to focus</p>
</body>
</html>
Here is a JSFiddle demo of the above code: http://jsfiddle.net/DvU63/
Why doesn't the focus go on the textarea box when the page loads? On clicking the link, the focus does go on the textarea box, but I also want the focus to go to the textarea box on page load. Why doesn't it happen?
Note: I am aware of the HTML5 autofocus attribute for textarea. But this question is about why the above JavaScript code does not do what I intend to do.
You're doing the .focus() statement from inside an onload handler that is itself defined inside an onload handler. This inner onload will not be called because by the time you define it the onload event will have occurred. Try this:
window.onload=function(){
var text = document.getElementById('text')
text.focus()
window.onhashchange = function() {
text.focus()
}
}
Your demo, updated: http://jsfiddle.net/DvU63/2/
do this
<script type='text/javascript'>
window.onload=function(){
var text = document.getElementById('text')
text.focus();
window.onhashchange = function() {
text.focus();
}
}
</script>
fiddle

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..
}

Why does positioning of <script> in HTML for window.onload event matters?

I have a form that hides a text input field dynamically, depending on the initial choice of an option field upon loading. After some trial and error, I realise that the <script> tag has to be placed below the <form> elements in order for this functionality to work:
<html>
....
<body>
....
<form>
<select name=choice>
<option value=0 selected>Default</option>
<option value=1>Others</option>
</select>
<input type=text name=others></input>
</form>
....
<script type='text/javascript'>
function init()
{
var A = document.forms[0].choice;
var B = document.forms[0].others;
if(A.options[A.selectedIndex].value == 0) B.style.display = 'none';
}
window.onload = init();
</script>
....
</body>
</html>
The event window.onload is a global event that is triggered after all resources of the page including DOM, images, frames, etc have loaded. Then, why is it still necessary for the <script> tag to be placed below the <form> elements?
Because your executing the init function instead assigning the pointer to the function...
Change:
window.onload = init();
To:
window.onload = init;
It's because of a typo in your code:
window.onload = init();
This is actually calling the init function immediately (and then setting window.onload to undefined). Try:
window.onload = init;
JavaScript and HTML works correctly. But I see some miss understand on your code.
window.onload = init();
This line means use execute init function immediately and set function result as onload event. That is the reason why it works when you place it under form element.

Categories

Resources