Difference between onclick and click using id JavaScript jQuery - javascript

I have been learning javascript and jquery for short period. I even know that the jquery is a library for the javascript. Now, I made a sample work on both and want to know the difference between the actions. Here is my code :
$(document).ready(function() {
$("#buttonOne").click(function() {
document.getElementById('paragraph').innerHTML = "You are yet to perform";
})
});
function checkButton() {
alert("Hello There");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="buttonOne" onClick="checkButton()">Click Me and Understand</button>
<p id="paragraph"></p>
index.html
<!DOCTYPE html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Wifi Wizard</title>
</head>
<body>
<br>
<br>
Start Wifi <input type="button" value="wifi" name="Wifi" id="wifi"/> <br>
Search Wifi <input type="button" value="search" name="Search" id="search"/> <br>
Scan Wifi <input type="button" value="scan" name="Scan" id="scan"/> <br>
<div id = "dataTable">
</div>
<input type = "password" name = "password" id = "passValue"></input>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
app.js
$(document).ready(function() {
$("#passValue").hide();
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
$('#wifi').click( function()
{
try {
WifiWizard.isWifiEnabled(win, fail);
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
function win(e) {
if(e) {
alert("Wifi enabled already");
}
else {
WifiWizard.setWifiEnabled(true, winEnable, failEnable);
}
}
function fail(e) {
alert("Error checking Wifi status");
}
function winEnable(e) {
alert("Wifi enabled successfully");
}
function failEnable(e) {
alert("Error enabling Wifi ");
}
$('#search').click( function()
{
try {
WifiWizard.listNetworks(listHandler, fail);
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
function listHandler(a){
alert(a);
}
$('#scan').click( function()
{
try {
WifiWizard.getScanResults({numLevels: 1},listHandler1, fail);
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
function listHandler1(a) {
alert(JSON.stringify(a));
var network_array = [];
var content = "<table>"
for (i = 0; i < a.length; i++) {
content += '<tr><td><button onclick="clickWifi(\'' + a[i].SSID + '\');">' + network_array.push(a[i].SSID) + '</button></td></tr>';
}
content += "</table>"
alert(network_array);
$('#dataTable').append(content);
}
function clickWifi(ssid) {
alert("Hello");
var networkSSID = ssid;
$("#passValue").show();
var passWord = document.getElementById("passValue");
var config = WifiWizard.formatWPAConfig(networkSSID, passWord);
}
WifiWizard.addNetwork(config, function() {
WifiWizard.connectNetwork(networkSSID, connectSuccess, connectFailed);
});
}
For above scenario, I have a made a button to call its click function dynamically, so please help as I have no idea whether the button declared is correct or wrong.
Here I have made a click function using id in jquery and onclick function using javascript. But the alert first pops up and then the jquery does it's work. I would like to know why doesn't jquery go first. Please give a suggestion.

https://jsfiddle.net/m3prjL8q/
here is the answer to the question in the comments. As far as the original post goes, it was answered in the comments, there is no need to repeat that.
When you use $(document).ready(function(){}) what you are doing is actually creating an event listener that will 'trigger' once the document is ready and giving it a handler function. This is yourJQuery function in the example. If you declare a function within the handler, this function is not accessible to the native javascript outside of the handler.
function yourJQuery(){
function innerDeclare(){
alert("I cannot be accessed outside of yourJQuery function");
}
}
innerDeclare();

IF i understood your Question correctly you want to know why html onclick method runs before jQuery click method.
That is simply because sequence you are adding click event on element.
HTML onclick method does not wait for DOM to render and attach event directly to the element.
But your jQuery method waiting for for Dom to be ready then it goes and attach the click event to element.
Hence events are getting executed in sequence.

For better performance, use the native JavaScript. For faster development, use jQuery. Check the comparison in performance at jQuery vs Native Element Performance.

Related

JQuery not working through Google's CDN

For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here

Pop-up based on location (Specifically the UK)

I have a very internationalised website, however I need to produce a pop-up specifically for our UK customers.
What I require is:
On page load: Is the user from the UK?
If yes then show div.
Else
Div remains hidden.
You can do this using freegeoip.
Since you mentioned that you want to use plain JavaScript (not jQuery), you should use JSONP to get the country:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>UK localisation</title>
</head>
<body>
<div id="myDiv" style="display:none">
<h1>Kittens</h1>
</div>
<script>
function toggleDiv(content) {
console.log(content.country_code);
if(content.country_code === 'GB') //Or GBR, or UK, I'm not sure.
{
document.getElementById('myDiv').style.display = "inline";
}
else
{
alert("You are not from UK, you are from " + content.country_code);
document.getElementById('myDiv').style.display = "none";
}
}
window.onload = function()
{
// create script element
var script = document.createElement('script');
// passing src with callback name
script.src = 'http://freegeoip.net/json/?callback=toggleDiv';
// insert script to document and load content
document.body.appendChild(script);
}
</script>
</body>
</html>

Calling same js function on pageload and on button click and displaying both functions called

I have a javascript function and I want to call the same function twice.
Once on page load and once on a button click.
I want the output as the function on page load will keep on running in backend and
display output and when button is clicked again function is called and its output
gets displayed.
Finally both functions output should be displayed.
This is what I have written but am not getting the output.
For e.g.
Javascript file: n.js
function webservice{
for(i=0;i<10;i++)
{
alert("some msg");
`enter code here`
}
html file n.html
<html>
<head>
<script type = "text/javascript" src="n.js"></script>
<script type="text/javascript">
window.onload=function() {
webservice();
}
</script>
</head>
<body>
<input id="button" type = "button" name = "webservice" value = "Call Webservice"
onClick="webservice()" />
</body>
</html>
Following code is working on my machine. I think you are missing () for function webservice(). so instead of webservice use webservice()
<html>
<head>
<script>
function webservice()
{
for(i=0;i<10;i++)
{
alert("some msg");
}
}
window.onload=function()
{
webservice();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input id="webservice" type = "button" name = "webservice" value = "Call Webservice" onClick="webservice()" />
</body>
</html>
Update:
if you write your onload function like this then you will be able to execute call 1 and call 2, butcall 2 will begin when call 1 loop is completed.
window.onload=function()
{
webservice('onload'); //call 1
document.getElementById("webservice").click(); //call 2
}
I think you code may be in wrong format.
function webservice{
for(i=0;i<10;i++)
{
alert("some msg");
`enter code here`
}
change to
function webservice(){
for(i=0;i<10;i++)
{
alert("some msg");
//enter code here
}
just add () after webservice. like webservice().

JavaScript DOM coding - 'undefined' error

I am having problem with this error:
'undefined' is null or not an object'
Can you please have a look and let me know. In my coding, I want to have simple DOM JavaScript code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
init();
function init()
{
getElementByTabIndex("4", "submit")[0].addEventListener("click", Verify, false);
}
function Verify() {
alert('done');
// all verification code will be here...
}
function getElementByTabIndex(index, type, node)
{
if (!node)
{
node = document.getElementsByTagName('body')[0];
}
var a = [];
els = node.getElementsByTagName('*');
for (var i = 0, j = els.length; i < j; i++)
{
if (els[i].tabIndex == index && els[i].type == type)
{
a.push(els[i]);
}
}
return a;
}
</script>
<body>
<input type="email" id="email" /><input type="password" id="pass" /> <label class="Login" for="login"><input value="Log In" tabindex="4" type="submit" id="login"></label>
</body>
</html>
You have to move you code at bottom or call init() after body is loaded.
Reason: you are trying to get elements even before they exists.
Eg :
<head>
<script>
var elm= document.getElementById('id');
//this will be always undefied, as trying to read element even before they exist
</script>
</head>
<body>
<div id='foo'></div>
<script>
var elm= document.getElementById('id');
//this wont be undefined
</script>
</body>
You call:
if (!node) {
node = document.getElementsByTagName('body')[0];
}
But your script runs before the DOM has finished loading, and so the body tag does not exist.
So node is undefined, and when you attempt the following, you get your error:
node.getElementsByTagName('*');
Run init() on document load, instead of immediately.
PS. jsfiddle and Firebug allowed me to debug this very quickly.
'body' isn't available to javascript at the time you are trying to call init().
call your init method when the dom has finished loading, like so:
window.onload = function (){
init();
}
note that in order to make this work across browsers (if you plan on using it outside your planned Safari extention) you will have to do some extra work. more info: http://www.javascriptkit.com/dhtmltutors/domready.shtml

FireFox capture autocomplete input change event

I'm trying to subscribe to change events on an input tag for an ajax auto complete form. These change events are not firing when the user clicks an autocomplete suggestion from FireFox.
I've seen fixes for IE, but not FireFox. You can view this behavior here
Steps to recreate:
type any input in one of the boxes and click submit.
Start typing the value again in the same box.
You should see the autocomplete suggestion box appear below the input box. Notice that clicking the suggestion does not fire the change event (it also doesn't fire the click event)
Currently my only option is to disable autocomplete on this field, but I do not want to do that.
Firefox 4+ fire 'oninput' event when autocomplete is used.
Here's some jQuery to make this more actionable:
$('#password').bind('input', function(){ /* your code */});
I've had the same problem.
Apparently, there is password manager debugging available
https://wiki.mozilla.org/Firefox:Password_Manager_Debugging
So I've found that for me DOMAutoComplete event got triggered and
I've managed to attach it sucessfuly to a field via jQuery's bind like
$('#email').bind('DOMAutoComplete',function() { ...
If it makes you feel better, it is a known bug
Proposed workaround: (Not mine, from here
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Mozilla Firefox Problem</title>
<script type="text/javascript">
function fOnChange()
{
alert('OnChange Fired');
}
var val_textBox;
function fOnFocus()
{
val_textBox = document.getElementById('textBox').value;
}
function fOnBlur()
{
if (val_textBox != document.getElementById('textBox').value) {
fOnChange();
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr>
<td><input type="text" id="textBox" name="textBox" onFocus="fOnFocus()" onBlur="fOnBlur()"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
</body>
</html>
Another Suggested work around. This time using polling, you can work it in exactly
the same way, checking for "changes" to your field. Tweak the poll value (default to
375ms for your own taste).
I've used jQuery and a jquery plugin someone wrote:
https://github.com/cowboy/jquery-dotimeout/
Git Hub Src: https://raw.github.com/cowboy/jquery-dotimeout/master/jquery.ba-dotimeout.js
<html>
<head>
<meta charset="utf-8">
<title>onChange() for Firefox / IE autofil get-around</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/~dsloan/js/ba-dotimeout.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var val;
var count=0; // used to illustrate the "poll count"
// when focusing on the element and typing
// (vs not focused)
// set a focus function to poll the input
$("#myname").focus(function() {
// start polling
$.doTimeout('checkname', 375, function() {
++count;
// no changes, just exit this poll
if($("#myname").val() == val) {
return true;
// store the value
} else {
val = $("#myname").val();
}
var str;
// do stuff here with your field....
if($(document.activeElement) &&
($(document.activeElement).attr('id') ==
$("#myname").attr('id'))) {
var len = $("#myname").val().length;
if(len == 0) {
str = 'Timer called, length 0...';
} else if(len < 2) {
str = 'Timer called, length < 2...';
} else {
str = 'Timer called, valid!';
}
}
// show some debugging...
$("#foo span").html(str+' (count: '+count+'): '+
$(document.activeElement).attr('id')+
', val: '+$("#myname").val());
return true;
});
});
// set a blur function to remove the poll
$("#myname").blur(function() {
$.doTimeout('checkname');
});
});
</script>
</head>
<body>
<form action="#" method=post>
Name: <input type="text" name="name" value="" id="myname" />
Scooby: <input name="scooby" value="" id="scooby" />
<input type="submit" value="Press Me!" />
</form>
<div id="foo"><span></span></div>
</body>
</html>
A possibly alternative: could you simply use a timer to tell when the value of the text box changes?
You're going to have to blur the input field and reset the focus to it. That's going to require a little trickeration though.

Categories

Resources