ajf1000 ajf1000 - 3 months ago 6
Javascript Question

Why is my JavaScript code refusing to run on my website?

The following is what my HTML document looks like:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="scripts/homepage-script.js"></script>
</head>

<body>
<div id="how-it-works">
<p>How It Works</p>
<img src="some-imageurl">
<div id="steps">
<p>Step 1</p>
<p>Step 2</p>
<p>Step 3</p>
</div>




And here is my script:

$('#steps > p').on('click' , function(){
$('steps > p').css('background', 'yellow');
});​


Why is my script not running on my website?

Answer

You need to wrap the jQuery in a document ready and you can use $(this) since it is targetted in the onclick event:

$(document).ready(function(){
     $('#steps > p').on('click',function(){
          $(this).css('background', 'yellow');
    });​
})

however what I would recommend is having a highlight class that is then toggled in the onclick event;

//CSS
.highlight{background:yellow}


$(document).ready(function(){
     $('#steps > p').on('click',function(){
          $(this).toggleClass('highlight');
    });​
})

Tht way you are adding / removing a class instead of altering the elements CSS.

If you want to add the highlight class to all the p's in that div as per @Phil comment -

$(document).ready(function(){
     $('#steps > p').on('click',function(){
         $('#steps > p').toggleClass('highlight');
    });​
})

$(document).ready(function(){
     $('#steps > p').on('click',function(){
          $(this).toggleClass('highlight');
    });
})
.highlight{background:yellow}
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="scripts/homepage-script.js"></script>
</head>

<body>
<div id="how-it-works">
    <p>How It Works</p>
    <img src="some-imageurl">
    <div id="steps">
    <p>Step 1</p>
    <p>Step 2</p>
    <p>Step 3</p>
</div>
  </body>
  </html>

Comments