sharf
sharf

Reputation: 2143

Need help understanding jQuery functions

I've spent a few days going over the guides on the jQuery site in an attempt to learn it. I have a pretty good grasp on it, and javascript. However, I'm trying to put it to use and I'm a bit confused.

here's the situation: I want to have a function that accepts parameters, and when called, will use those parameters to set the inner html of a div.

In regular JS I would do something like:

function showMessage(type, title, message){
    div.innerHTML = "hello world!";
}

It would obviously use the parameters but for the sake of simplicity I didn't.

I know in jQuery, to do the same thing you would do:

$('#id').html('Hello world!');

However, to do that I'd need it in a document ready function. I've also experimented with

$('#close').click(function( event ) {
    do stuff;
} 

With the original JS function, I could simply do an

onClick="showMessage"

Is there a way to call functions like that in jQuery? or do I need to use .click listeners? I don't know a terrible lot about jQuery, and I don't know everything that my system will need to be able to do in the future, so I'd rather have a way to call the function when I need it. Also, how do I pass parameters to the jQuery function?

Upvotes: 0

Views: 115

Answers (4)

deviloper
deviloper

Reputation: 7240

using a $(document).ready() function triggers the page and elements to listen to the defined events to occur and run functions accordingly. yet you can use JQuery facilities together with JavaScript style of scriptings.

following might help:

<input type=text onchange="getName(this.value,'link.php');" />

JS:

function getName(val, href){
    var link = href +'?name='+val;
    $('#result').load(link); // JQuery function
}

Upvotes: 0

akbarbin
akbarbin

Reputation: 5105

The concept on creating function when using document ready:

$(document).ready(function(){
  //call function
  showMessage("alert", "hello", "message")
})

function showMessage(type, title, message){
  $('#id').html('type is :' +type+ ' title is :' +title+ 'message is'+ message);
}

Upvotes: 2

kyler
kyler

Reputation: 633

Use .click() or .on() listeners in order to call your functions for the sake of keeping javascript calls out of your html

Also, how do I pass parameters to the jQuery function?

you pass them into the function using an anonymous callback on your click event

function showMessage(param1, param2) {
    //do stuff with your params
}

jQuery('#id').click(function() {
    showMessage(param1, param2);
});

Upvotes: 2

Jay
Jay

Reputation: 6294

Is this what you're looking for?

$(document).ready(function () {
    $('#close').click(function() {
        showMessage('id', 'Hello world!');
    } 
});

function showMessage(id, message){
    $('#' + id).html(message);
}

Upvotes: 1

Related Questions