style237
style237

Reputation: 69

Console not logging after onClick event

I have HTML div that resemble a star rating system.

I'm trying to simple test some javascript so that when I click a star then the console logs 'hello'.

<div class=rating>
    <div class="ratings_stars" data-rating="1"></div>
    <div class="ratings_stars" data-rating="2"></div>
    <div class="ratings_stars" data-rating="3"></div>
    <div class="ratings_stars" data-rating="4"></div>
    <div class="ratings_stars" data-rating="5"></div> 
</div>

$('.ratings_stars').on('click', function() {
    console.log('Hello');
});

The JS is in a separate file and I've linked that fine.

Upvotes: 2

Views: 1518

Answers (3)

Willem van der Veen
Willem van der Veen

Reputation: 36620

Use MichaelvE answer for the code. I want to add the following, in your code:

$(document).ready(function() {
  $('.ratings_stars').on('click', function() {
    console.log('Hello');
  });
});

The $(document).ready(function() {/* code to be executed */}); part is necesarry for the DOM to build up. The DOM is an in memory tree like representation of an HTML file which we can alter programmatically via JS/JQuery. What JQuery does under the hood is adding an event listener to all all DOM elements which contain the rating_stars class.

The JS engine can execute code before the DOM is built up. This will lead to an error because JQuery tries to attach an event handler to a non existing DOM element.

Upvotes: 0

style237
style237

Reputation: 69

All sorted.

Needed to wrap in a DOMReady Event.

Thanks for the help everyone.

$(function () {
$('.ratings_stars').on('click', function() {
    console.log('Hello');
});
});

Upvotes: 0

MichaelvE
MichaelvE

Reputation: 2578

Your class needs to be in quotes, and place your jQuery listeners in a document ready function:

$(document).ready(function() {
  $('.ratings_stars').on('click', function() {
    console.log('Hello');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rating">
  <div class="ratings_stars" data-rating="1">Click me</div>
  <div class="ratings_stars" data-rating="2">Click me</div>
  <div class="ratings_stars" data-rating="3">Click me</div>
  <div class="ratings_stars" data-rating="4">Click me</div>
  <div class="ratings_stars" data-rating="5">Click me</div>
</div>

Upvotes: 2

Related Questions