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?
4 Answers 4
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);
});
1 Comment
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);
}
1 Comment
Is this what you're looking for?
$(document).ready(function () {
$('#close').click(function() {
showMessage('id', 'Hello world!');
}
});
function showMessage(id, message){
$('#' + id).html(message);
}
3 Comments
onclick="showMessage('id', 'Hello World!');" is bad form. Wire up your events and the like through straight JavaScript.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
}
onclickof$('#close').click()is also valid. But the latter one can separate Javascript from HTML code, which makes the structure easier to manage.$(document).ready()turns it into a jQuery object, with or without jQuery, you can still do it.