Goal#
Overview#
In the last step, We learned that jQuery is easy writing alternative of javascript.
So, let's replace the javascript code which we learned with jQuery.
Preparation#
- Make
jquery-test
folder - Make
jquery-test1.html
inside it
We will start from this code.
So, copy and paste this code
jquery-test1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="demo">Click here</div>
<script>
let demoElement = document.getElementById("demo");
demoElement.onclick = function changeContent() {
demoElement.innerHTML = "Help me";
demoElement.style = "color: red";
};
demoElement.onmouseover = function () {
console.log("Hello~!");
};
</script>
</body>
</html>
Import jquery#
To use jQuery, we need to import jQuery.
https://jquery.com/
jquery-test1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="demo">Click here</div>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"
></script>
<script>
let demoElement = document.getElementById("demo");
demoElement.onclick = function changeContent() {
demoElement.innerHTML = "Help me";
demoElement.style = "color: red";
};
demoElement.onmouseover = function () {
console.log("Hello~!");
};
</script>
</body>
</html>
jQuery syntax#
First, let's check jQuery syntax.
$(selector).eventname(function(){
})
For example
$("p").click(function() {
})
$(".test").mouseover(function() {
})
$("#demo").click(function() {
})
Ref: https://www.w3schools.com/jquery/jquery_syntax.asp
Replace onclick
, innerHTML
, style
#
The most important things is always googling.
So, this code becomes
Javascript
let demoElement = document.getElementById("demo");
demoElement.onclick = function () {
demoElement.innerHTML = "Help me";
demoElement.style = "color: red";
}
becomes
jQuery
$("#demo").click(function() {
$("#demo").html("Help me");
$("#demo").css({ color: "red" });
});
Check it works as before...
Repalce onmouseover
#
Googling "jQuery onmouseover equivalent" => https://api.jquery.com/mouseover/
So,
pure javascript
demoElement.onmouseover = function () {
console.log("Hello~!");
};
becomes
jQuery
$("#demo").mouseover(function() {
console.log('Hello~!');
})
Check it works as before...