Skip to main content

Posts

Showing posts with the label common jQuery events

Three Most Common jQuery Events Part Three: On()

On() On() works similarly to addEventListener. It lets you specify the type of event to listen for. If we want to style the h1 text content when h1 is clicked, we could write: $("h1").on("click", function(){ $("h1").css("color", "green");}) Inside on(), we give the type of event we want to listen for, in this case is "click". Then, we pass a function to change the h1 style when the event happens. If we want to bold the button text when the mouse is on that button, we will select "button", then set "mouseenter" as event type, and pass a function which will make the text bold. If we want the bold button back to normal, we only need to change the "mouseenter" to "mouseleave", and change "bold" to "normal". What's the difference between on() and click()? In most case, click() and on("click") will both get the job d...

Three Most Common jQuery Events Part Two: Keypress()

Keypress In jQuery, keypress() method is a quick and easy way to add a key press listener to element(s). I updated the HTML a little bit by adding a simple text input.  If I want to get a print message every time when I press the key in the input, I will write keypress() function: $("input").keypress(function(){ console.log("You Pressed A Key!");}) So no matter what key I press, the console will print out the message right after I pressed the key. If we want to listen for a key press only we hit the "Enter" key, we need to check the key code for enter key first.  The key code for "Enter" is 13. Therefore, we can write an if function in the keypress(): $("input").keypress(function(event){ if(event.which === 13) { alert("You Hit Enter");} })

Three Most Common jQuery Events Part One: Click()

The course summarized three most important and useful jQuery events which could use 99% of the time. These three events are: click(), keypress(), and on(). Click In jQuery, click() method is a quick and easy way to add a click listener to element(s). $("selector").click(function(){ run some code}); Recall the click event in JavaScript, we have to do document.querySelector() first, then addEventListener, and give a function. The jQuery one looks much easier to apply. I create a simple HTML page with some buttons. I will show you how to use click() method to make actions on page. Then, I check whether jQuery file is connected correctly. If I want to get an alert when I click on h1, I will use "$" to select h1, then add alert message inside click() function:  $("h1").click(function(){ alert("h1 is clicked");}) As the result, when you click the h1 text, the page will pop up the alert message. We can write the ...