Console not displaying any logs following the occurrence of an onClick event

One interesting feature I have on my website is an HTML div that functions as a star rating system.

Currently, I am experimenting with some JavaScript code to test its functionality. My goal is for the console to log 'hello' whenever I click on one of the stars.

<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 JavaScript code is stored in a separate file which I have successfully linked to.

Answer №1

Ensure that your class is enclosed in quotation marks, and remember to include your jQuery event handlers within 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>

Answer №2

Everything is now in order.

Just had to encase it in a DOMReady Event.

Appreciate the assistance from all of you.

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

Answer №3

Refer to MichaelvE's solution for the initial code implementation. In addition, please include the following snippet within your existing code:

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

The

$(document).ready(function() {/* code to be executed */});
portion is crucial for allowing the DOM structure to fully load. The Document Object Model (DOM) serves as a representation of the HTML elements in memory, enabling us to dynamically modify it using JavaScript/jQuery. By internally assigning event handlers to all elements with the class rating_stars, JQuery facilitates interaction with these specific elements.

Executing JavaScript code prior to the complete DOM construction can result in errors, as JQuery attempts to bind an event handler to elements that have not yet been created.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most streamlined way to send data from HTML forms using solely JavaScript?

I currently employ jQuery to transmit data from my HTML forms and then I utilize PHP to save it in my database. Below is the code snippet that I am using: HTML FORM: <form id="formpost" action="" method="post" onsubmit="return false"> <input t ...

Is there a way to switch out the WordPress page title for an image instead?

I am trying to change up the appearance of my WordPress site by replacing the text on page titles with images. Working on a child theme locally, I need to customize each page individually as they will have different images. The current state is as follows ...

Insert HTML content into an iframe with a callback function

We are receiving information from the backend server and need to transfer it to an iframe. In order to accurately set the height of the iframe to match the content, we must wait for the content to be loaded into the iframe. However, this process may not ha ...

Guide to fetching and returning data from AJAX using a function

In my JavaScript file, I have a function that retrieves a value asynchronously from the server: function retrieveValue(userId) { $.ajax({ type: "POST", url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles", data ...

Validating the length of form inputs and selected items from a dropdown menu

I have the following form and I am attempting to validate its states as follows: themeName is required and should have a minimum of 4 characters. themeLangFrom selected value cannot be the same as themeLangTo (and vice versa). I want to display a span er ...

Transforming a simple MySQL query into a structured nested JSON format

Is there a way to easily reorganize data without using complex for loops (perhaps with Underscore.js or refining the MySQL query)? I have data formatted like this: [ { "J_NUM": "BOAK-1212", "X_DUE_DATE": "2012-06-20T00:00:00.000Z", "X_LEAD_T ...

HTML5 Positioning Timeout

While working on my project, I incorporated the HTML Geolocation feature. However, I have observed that it is not always dependable. I am looking for a solution to add a backup plan that will time out after x seconds and display an error message. Any sugg ...

Angular failing to append hash to ng-href in browsers that do not support it

When I attach an ng-href to a link like this: ng-href="{{post.btn.url}}" The resulting value is: ng-href="/news/some-post" In browsers that do not support html5 mode, these links do not work properly because they require a #. How can I handle this in I ...

Can HTML Elements be used within a Contenteditable section?

I am facing an issue with a contenteditable tag on my website. Users are unable to type code into the tag and have it display as an actual element instead of just text. Is there a way for users to input full, working HTML elements in a contenteditable box ...

Navigating through complex immutable entities

I am having trouble working with multidimensional immutable arrays. I would like to make my array immutable, but I'm not sure how to do so. Consider the following data structure: // data { // item { name: someName, todos: [ ...

Stopping a JavaScript promise.all() based on a certain condition

Here's a snippet of code I'm working with: let promiseList = [] for (let i in data) { let promise = checkIfMember(data[i].tg_id, chatId).then(res => { if (res) { //if the user has a undefined username ...

What is the best way to incorporate these elements into my Bootstrap 5 navbar design?

This is the current layout of my navbar, with the logo in the center. I now want to enhance it by adding a search bar and some icons similar to this example: ideal navbar Here is my current navbar for reference: My current navbar <header> <n ...

Is it possible for numerous identical components to trigger the display of the identical modal on a single webpage?

I am currently utilizing Vue in my project and I have a component that displays a button. When this button is clicked, it triggers a modal to open which is also part of the same component. The functionality works as intended. However, if there are multipl ...

Calculating a 30-minute interval between two given times using JavaScript/jQuery

My goal is to generate a list of times between a specified start and stop time, with half-hour intervals. While I have achieved this using PHP, I now wish to accomplish the same task using JavaScript or jQuery. Here is a snippet of my PHP code which may ...

Having trouble with Node.js executing commands in the console

I've been following some tutorials on YouTube to learn how to create a real-time chat using Node.js from the phpacademy channel. Currently, I'm stuck at the step where I need to run my server.js file in the console. When I enter the command ...

The AWS API Gateway quickly times out when utilizing child_process within Lambda functions

I'm encountering an issue with my Lambda function being called through API Gateway. Whenever the Lambda triggers a spawn call on a child_process object, the API Gateway immediately returns a 504 timeout error. Despite having set the API gateway timeou ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...

Can other JavaScript event listeners be synchronized with an asynchronous event?

My goal is to manipulate a web page using Tampermonkey where there is a button with certain event listeners followed by a redirect. Is it possible for me to insert my own click event handler into the button, which triggers an AJAX request and waits for it ...

Retrieving the original state value after updating it with data from local storage

Incorporating the react-timer-hook package into my next.js project has allowed me to showcase a timer, as illustrated in the screenshot below: https://i.stack.imgur.com/ghkEZ.png The challenge now lies in persisting the elapsed time of this timer in loca ...