Gareth Compton
Gareth Compton

Reputation: 149

How to make Javascript functions "defined" while using jQuery?

Here were many problems that occured and I found a way to make them 'validated' but, is this safe? if not can you help me make it right?

$('document').ready(function{
    var $demo = $('demo');
    $demo.onclick(function runAlpha(){
        //do something with alpha
    });
    $demo.onclick(function runBeta() {
        //do something with beta
    });
});

function runAlpha(){}
function runBeta(){}

the functions outside of the jquery are left blank to be a null and javascript recognizes that its defined. but is there a way to make this more effective? and if I do add anything in the javascript section, will it cause code conflict? or will it be added in?

Upvotes: 0

Views: 38

Answers (1)

dave
dave

Reputation: 64687

A little confused about what you are trying to do. The usual way of writing jQuery would be to use anonymous functions, like this:

$('document').ready(function{
    var $demo = $('demo');
    $demo.on("click", function() {
        //do something with alpha
    });
    $demo.on("click", function() {
        //do something with beta
    });
});

If you want named functions, you would probably do it like this:

$('document').ready(function{
    var $demo = $('demo');
    $demo.on("click", runAlpha);
    $demo.on("click", runBeta);
     function runAlpha(){
      //do something with alpha
    }
    function runBeta(){
      //do something with beta
    }
});

It sounds like you want to be able to call runAlpha or runBeta outside of the $(document).ready portion. The way I would normally do this would be:

$('demo').trigger("click");

If you want to call the function directly, move the function definitions outside of the closure:

    $('document').ready(function{
    var $demo = $('demo');
    $demo.on("click", function() {
        //do something with alpha
    });
    $demo.on("click", function() {
        //do something with beta
    });
});

function runAlpha(){
    //do something with alpha
}
function runBeta(){
     //do something with beta
}

I'd personally do it the first way, as I don't like to "pollute" the global namespace, but it's really your call.

Upvotes: 3

Related Questions