R K R K - 25 days ago 19
CSS Question

style code in jQuery not working

<!DOCTYPE html>
<html lang="en">
<head>
<title>
</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
</head>
<body>
<button id="myButton">My Button</button><br /><br />
<span id="myPara"> My paragraph</span>
<script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
<script type="text/javascript" src="js/custom.js" ></script>
</body>
</html>


below is code in
custom.css


#myPara{
border: 1px solid black;
color: black;
padding: 5px;
}


below is code in
custom.js


$('#myButton','#myPara').on('click',function(){
$(this).css('border-color','white').css('background','black').css('color','white');
});


I want to apply the given css as shown in the jquery code.

It also isn't giving any error in console, which makes it harder for me to find the error.

In my browser no css effect is showing on click.

I am a beginner in jQuery.

Answer
$('#myButton','#myPara').on('click',function(){

In this line, the first argument is a CSS selector and the second argument is used for context. You probably wanted this instead:

$('#myButton,#myPara').on('click',function(){

You can find out more about how the $() function works here.

Comments