How do you create a function in jQuery, call it, and pass a variable to it? Here it is in Javascript style:
<script type="text/javascript">
function popup(msg) {
alert(msg);
}
</script>
Then you would simply include the event in the HTML:
<html>
<input type="submit" onclick="popup('My Message')" />
</html>
What is the jQuery equivalent to doing this? From all the “newbie” tutorials, they are all static functions that do not accept variables. For example:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
alert('hello, world');
});
});
</script>
I want to be able to dynamically include different messages. The code above affects all buttons and spits out the same message of ‘hello, world’.
If you want the message to be dynamic, you’re going to want to use
data-attributes:Then in a separate javascript file:
Now the function will execute any time a button with class
.message-buttonis clicked, and it will use the custom attribute data-message to display a message.Hope this helps! 🙂
Update:
Note that it’s considered best-practice to do javascript unobstrusively. Some people have mentioned still using the
onclickattribute like you did in your example, don’t do that. Bind the event like I’ve shown here using jquery’s.on('click', function(){})method.If your click item is an anchor tag
<a>then you can prevent the href from being followed if you want, by usinge.preventDefault:Also in case you need to know, the
$('.message-button')is using css selectors to grab dom elements. Any valid CSS selector will normally work in there.Step-by-step
First, we need to wrap all of our code in a function provided by jQuery that waits until the document is ready to handle javascript actions and dom manipulation. The long-form version is
$(document).ready(function(){ /* CODE GOES HERE */ })but the version I’ve used is a shortcut$(function({ /* CODE GOES HERE */ }):Next, we need to bind an event to our button. Since we’ve given it the class
.message-button, we can use jQuery to grab that element and bind the ‘click’ event to it:Inside of event handlers
thisis re-bound to point directly to the HTML element that triggered the event. Wrapping in $() gives us access to jquery methods. Thus: $(this) is used very frequently. jQuery gives us the.data()method to access anydata-*methods on the element and give us the value, which is what thealert()is doing.