-1

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.

learner
  • 177
  • 19
  • because of jquery dom loaded time your native function works first – Özgür Ersil Jun 29 '16 at 11:09
  • what if I made like this, the alert goes for the jquery and the text goes for the javascript and if I make the javascript function inside the $(document).ready(function()), why we get error as that the checkButton() javascript function is not defined. – learner Jun 29 '16 at 11:11
  • 4
    Possible duplicate of [jQuery.click() vs onClick](http://stackoverflow.com/questions/12627443/jquery-click-vs-onclick) – Hozeis Jun 29 '16 at 11:13
  • about the error I asked what if the javascript function is declared inside the jquery syntax and why we are getting the error – learner Jun 29 '16 at 11:17
  • When you declare a function within the jQuery's $(document).ready(function(){}) you are essentially declaring a function within a function, which makes it inaccessible to the outer world, as far as i know. – Dellirium Jun 29 '16 at 11:19
  • Here is a fiddle, run it and you will see that it works, it is exactly the same code that I've given you for the function (only difference is the callWifi function doesnt address the WifiWizard because I commented it, but its not relevant, it is being run. https://jsfiddle.net/8k52hq25/ I literally took the function call now, called it with some parameters, to simulate your application , and it works on the PC, your problem is not in the javascript/code, it is somewhere else, thus I cannot help you. – Dellirium Jun 29 '16 at 14:19

3 Answers3

0

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();
Dellirium
  • 1,362
  • 16
  • 30
  • what if I'm calling a function from a button and the button is inside a variable in javascript.Would you please explain that or how to do that, example: var button = ""; and in function checkButton1(){alert("Im here too")}, how does this work? – learner Jun 29 '16 at 11:28
  • What do you mean by 'button is inside a variable' ? What you just put in the variable is a 'string' you cannot really put a button into a variable. You can put a reference to a DOM element which is the button, but it doesn't really change anything. Can you try to explain what are you trying to achieve here? A button can have it's onclick event bound anywhere you want, be it inside the jQuery's document ready handler, or outside of jQuery at all, but what do you want to do with the binding? – Dellirium Jun 29 '16 at 11:33
  • var content = "", this works fine in my html page describing a html table inside a variable and it works fine too, but the same button inside a variable and its click event, will work?
    – learner Jun 29 '16 at 11:36
  • I do not understand you, at all. Again, you cannot put a button, table, or any other element into a variable. You can put it's reference. But what you are doing is just putting strings. `""` is not a table it is a string of characters that writes `
    ` might as well be `""` as far as javascript is concerned. To reference a DOM element use one of the selectors, such as `document.getElementById( 'elementsID' )` or `.getElementsByClassName( 'className' )[ arrayIndex]` or `getElementsByTagName` same principal. Puttin a string means nothing.
    – Dellirium Jun 29 '16 at 11:41
  • Explain to me what your goal is and I will give you a concrete example that works (got nothing to do, and have to sit here for another 3 hours), but give me what you want and need, not how you want it done. – Dellirium Jun 29 '16 at 11:43
  • k, please tell then how to dynamically create a button with its onclick function or provide a link and I will also change my question please have a look. – learner Jun 29 '16 at 11:45
  • please have a look at my program, what is the mistake I have done over there. please explain and I want that button to be with the table tr,td because it is going to replicate the array as a list. – learner Jun 29 '16 at 11:55
  • Remove the spaces between 'onclick', '=' and 'functionName', should work, but it is not the proper way to do things, just saying. – Dellirium Jun 29 '16 at 11:58
  • I wanted to reply, but it said "post has been deleted" anyways, yes your issue is not in the spaces, spaces do not matter at all it seems. I cannot "run" this one on fiddle because I do not have your parameters and the structure of your "a" object. What is exactly the issue here, you do not see buttons created? Or they are created but do not work, what happens? I mean the entire code is a big mess, it is hard to deduce what was the point there? I can give you my version of what I think it should be. – Dellirium Jun 29 '16 at 12:33
  • K, @Dellirium, I'm trying to create a wifi Application using jquery or javascript, 'a' are the links after you get from the scan results. Im doing this using cordova and cordova plugin 'wifiwizard'. Im just doing a wifi application which should be as same as the wifi application in our smart phones. – learner Jun 29 '16 at 12:39
  • In this fiddle I've given you two examples of how I'd do it, try it, hope it helps: https://jsfiddle.net/r3cr50jm/ – Dellirium Jun 29 '16 at 12:45
  • which fiddle are u talking about. If you want I can post the entire program of what I did so far. Please help and where is ur latest fiddle – learner Jun 29 '16 at 12:47
  • Fiddle is linked in the comment, at the very end. It will not work on the fiddle.net, but copy one of the two solutions to your code and try it. Should work there. – Dellirium Jun 29 '16 at 12:50
  • so as you said in the example, so how can I develop the application as there is no sample in the internet and it will be difficult for me as im new to these stuffs. If you need I can post the entire program – learner Jun 29 '16 at 12:54
  • You develop something by solving one issue at a time, it is irrational to expect me to develop an application for you. So to a point, the issue with the buttons, their events and such, did you try to copy-paste the code and run it to see if it work? If it doesn't what are the issues? – Dellirium Jun 29 '16 at 12:55
  • I'm not asking u to develop the entire app, that's not good for me, then what i will learn to become a programmer like you guys, but im asking u what may be the better way to do it or what are the stuff i need. – learner Jun 29 '16 at 12:58
  • Did the way I wrote it in the example make it work and if it didn't what was the issue? One issue at the time, cannot solve the "what do I need to make an app", step by step, does it work now? – Dellirium Jun 29 '16 at 12:59
  • No, its the same still. If you want I will post the code for your understanding. – learner Jun 29 '16 at 13:02
  • You can post the code, but it will only clutter us, describe to me how the program behaves, what happens, "same still" doesn't mean much to me, do it more precise: "button clicks dont work", "buttons are not shown", "nothing is shown". I need to have more info before I can help you. Best thing to do would be to press CTRL + SHIFT + I and switch to the console tab, see what the error message is, write that, help me help you. Be as descriptive as possible. – Dellirium Jun 29 '16 at 13:05
  • actually, I can only see it in my mobile because it is done using cordova for mobile applications and the error is "click is not working".Please have a look at the question – learner Jun 29 '16 at 13:08
  • Updated the fiddle here: https://jsfiddle.net/r3cr50jm/1/ Try it now, the error was in the parsing of the onclick event's string into HTML. – Dellirium Jun 29 '16 at 13:26
  • its not working still, I'm getting the buttons but can click and no reaction even the alert was not poping. – learner Jun 29 '16 at 13:35
  • Where is your script located in your document, in ? Move it to the bottom of the tag. – Dellirium Jun 29 '16 at 13:44
  • it is located at the bottom of the only, please have a look at the question, I have uploaded already my index.html and app.js – learner Jun 29 '16 at 13:50
  • You did not change the code to what I said in the last fiddle. Your code: ` – Dellirium Jun 29 '16 at 13:56
  • the question I posted contains my original code, I have tried both the fiddles you gave but no change. – learner Jun 29 '16 at 13:58
  • change your original code with regards to what I wrote in the last comment, also update the code in your post. Then test if it works, it should. And what I want you to do now is give me the error message your browser sends. CTRL + SHIFT + I and open the console. I believe that F12 also opens the console, and write exactly what the message is when you click the button. – Dellirium Jun 29 '16 at 14:01
  • It is for our mobile devices, I cant see it in the console in a browser, I can only run in the mobiles and plz have a look at my code and I have updated the code as well. And in the mobile you dont have any console to check.You can only install the application – learner Jun 29 '16 at 14:07
0

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.

Sandeeproop
  • 1,756
  • 1
  • 12
  • 18
  • Please have a look in the updated question, my dynamically created button and its onclick event. please correct it – learner Jun 29 '16 at 11:50
-2

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