Transforming jQuery into classic JavaScript traditions

I want to convert the code below into pure JavaScript.

document.addEventListener('click', function(event) {
  if (event.target.classList.contains('savedPlayer')) {
    event.preventDefault();
    let searchText = event.target.textContent.replace(" ", "%20");
    console.log(searchText);
    //resetState();
    //renderPlayerBtns();
    //searchBallDl(searchText);
    //searchYouTube(searchText);
    //searchGiphy(searchText);
  }
});
div {
  height: 20px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div class='savedPlayer'>savedPlayer 1</div>
<div class='savedPlayer'>savedPlayer 2</div>
<div class='other'>other</div>

I have some specific questions regarding the click event. Can a JS event listener have multiple arguments passed into it? What is the JS alternative to $(this)?

Appreciate the assistance!

Answer №1

When delegating the click event to .savedPlayer, you can apply the same approach with delegate event.

Since it triggers the click event on every element within the document, it's essential to verify if it is the intended target using

if (event.target.classList.contains('savedPlayer'))
.

Instead of using $(this).text(), you can opt for event.target.innerText. Similarly, if you were using $(this).html(), you should now use event.target.innerHTML.

document.addEventListener('click', function(event) {
  if (event.target.classList.contains('savedPlayer')) {
    event.preventDefault();
    let searchText = event.target.innerText.replace(" ", "%20");
    console.log(searchText);
  }
});
div {
  height: 20px;
  border: 1px solid;
}
<div class='savedPlayer'>savedPlayer 1</div>
<div class='savedPlayer'>savedPlayer 2</div>
<div class='other'>other</div>


Edit Following the advice of @VLAZ, the code has been updated to a more generalized delegate event.

function delegate(eventName, selector, handler) {
  document.addEventListener(eventName, function(event) {
    if (event.target.matches(selector)) {
      handler(event);
    }
  });
}

delegate('click', '.savedPlayer', function(event) {
  event.preventDefault();
  let searchText = event.target.innerText.replace(" ", "%20");
  console.log(searchText);
});

delegate('click', '.other', function(event) {  
  alert(event.target.innerText);
});
div {
  height: 20px;
  border: 1px solid;
}
<div class='savedPlayer'>savedPlayer 1</div>
<div class='savedPlayer'>savedPlayer 2</div>
<div class='other'>other</div>

Answer №2

To enhance your 'savedPlayer' elements with a listener and retrieve the clicked element from within the callback function, follow these steps:

document.querySelector('.savedPlayer').addEventListener(
    'click',
    function() {
        alert(event.target.innerHTML);
    }
);

Answer №3

This isn't the traditional JavaScript from the early days when jQuery was created, lacking the modern features we have now. However, what you see here is a Vanilla JS adaptation of your code snippet.

I implemented deferred event handling using a function that takes a class name as a parameter. Give it a try (only the button "two" will respond to clicks):

document.querySelector('body').addEventListener('click',evHandler("savedPlayer"));

function evHandler(cls){
 return function(ev){
  if (ev.target.classList.contains(cls)) {
   ev.preventDefault();
   let searchText = ev.target.textContent.replace(" ", "%20");
   console.log('action with: '+searchText);
  }
 }
}
<button class="test">one</button>
<button class="savedPlayer">two</button>

Answer №4

When it comes to handling events, event.target is a popular choice. Here is an example of how you can use it:

document.addEventListener('click', function (event) {
    event.preventDefault();
    let searchQuery = event.target.innerHTML.replace(" ", "%20");
    ...
});

If you have multiple arguments to handle, you can create a separate function and call it in your onclick event.

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

Updates to the AngularJS model are not appearing in the user interface

Despite executing the controller code, the values in the UI remain unchanged. The initial values are displayed without any issue. I've attempted to call $scope.$apply() at the end of each function (submit and transfer), but it didn't resolve the ...

Verification is required for additional elements within the div block once a single checkbox has been selected

Currently, I am working in PHP using the CodeIgniter framework. I have a question regarding implementing a functionality with checkboxes and validation using jQuery. Here is the scenario I want to achieve: There are four checkboxes, and when one checkbox ...

Is it possible to simultaneously run watchify and node-sass watch together?

Currently, I am utilizing npm scripts in conjunction with watchify and node-sass while incorporating the -w parameter. I am curious if it is feasible to execute both of these 'watch' commands simultaneously. Would this setup ensure that only sty ...

Incorporate child routes within a React component

I've been attempting to include <route> in a component within a routers component, but it doesn't seem to be working. Can anyone provide some assistance? My login page currently has a form and I'd like to switch that out with routes. ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

Using JavaScript to detect the Facebook like button on a webpage

I am currently developing an application for Facebook using HTML and Javascript. My goal is to be able to detect when a user clicks the "Like" button on my company's Facebook page without needing to embed a separate "Like" button within my app itself. ...

Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application. Below is the code snippet that I have tried so far: Component.ts : ngOnInit() { this.loadScript(); // also attempted with ...

Error: The axios instance for the app is not defined in Vue.js 3

My main.js file is responsible for creating an app and adding components like router, store, and axios. Here is how I'm globally adding axios: import {createSSRApp, createApp, h} from 'vue'; import axios from 'axios' const r ...

Sharing state between two functions in React using Hooks

Coming from a background in Vue, I am struggling to comprehend how to conditionally show something when the HTML is fragmented into different parts. Imagine having this structure: import React, { useState } from "react"; const [mobileNavOpen, setMobi ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Is there a way to invoke a function using $scope within HTML that has been inserted by a directive in AngularJS?

After moving the following HTML from a controller to a directive, I encountered an issue where the save button no longer functions as expected. I attempted to change the ng-click to a different function within the directive code, and while that worked, I u ...

Styling of checkboxes in jQuery Mobile is missing after an AJAX request

I am currently working on implementing an ajax call to retrieve a list of items from a json array and display them as checkboxes. While the items are loading correctly, they lack the jquery mobile styling. $(document).ready(function(){ ...

Tips for utilizing the find function with nested documents in MongoDB in conjunction with Next.js?

I have structured my data in such a way that it is obtained from localhost:3000/api/notes/[noteTitle]/note2 { "data": [ { "_id": "62ff418fa4adfb3a957a2847", "title": "first-note2" ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Unexpected glitch: three.js texture turns completely black

I am currently working on a simple geometry box that I want to decorate with a texture. However, the box seems to be invisible or completely black. This issue is related to a previous question that can be found here. Following the answer provided by gaitat ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

Steps to add an SVG to a DIV when clicked

This script is fully functional and produces the desired results. var play = function(){ $( this ).click(function() { console.log( "Test" ); }); } I am looking to replace the console.log( "Test" ); with an SVG that will display in the cli ...

Instantly summing up two numbers with javascript

In my web development work using Visual Studio 2008, I encountered an interesting challenge. On a webpage, I have three textboxes labeled "Price," "Quantity," and "Amount." The task at hand is to calculate the value of "Amount" by multiplying the values ...