Pranshu Shah Pranshu Shah - 24 days ago 7
HTML Question

My JavaScript isn't working

Here is the html code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="hello.js"></script>
<title>Title</title>
</head>
<body>
<form action="#">
<p>Name:<input type="text"/></p>
<p>Password:<input type="text"/></p>
<p><input id= "newsletter_button"type="button" value="CLICK ME"/></p>

</form>

</body>
</html>


And this is the JavaScript:

$(":text").focusin(function () {
$(this).css("background-color", "red");
});
$(":text").blur(function() {
$(this).css("background-color", "#fff");
});


hello.js and index.html is in same file. I think there is some problem in jQuery.

Answer

Either put your hello.js at the end before </body> or wrap it with

$(document).ready(function(){
$(":text").focusin(function () {
  $(this).css("background-color", "red");
});
$(":text").blur(function() {
  $(this).css("background-color", "#fff");
});
});

What it does is executes the code once full page is loaded. Otherwise if you put it before the ":text" DOM object is loaded it will encounter DOM object not defined error.

Also you have a markup error

<p><input id= "newsletter_button"type="button" value="CLICK ME"/></p>

Put a space before type:

<p><input id= "newsletter_button" type="button" value="CLICK ME"/></p>