Issue with .click() function in JQuery not functioning

My View has a map with markers that display pop-ups when clicked, which is functioning correctly.

Below is the code for the map functionality:


export function all_hotels_map_results(): void {
    Helpers.set_currency_settings();
    const json = gon.hotel_info;
    const token = "***********";
    const centerLatlng = new mapboxgl.LngLat(gon.destination_city.lng, gon.destination_city.lat);
    mapboxgl.accessToken = token;
    let map = new mapboxgl.Map({
        container: "map-canvas",
        style: "mapbox://styles/mapbox/streets-v9",
        center: centerLatlng,
        zoom: 9
    });

    map.addControl(new mapboxgl.NavigationControl());
    map.on('load', function() {
        $.each(json, function(i, item) {
            let myLatlng = new mapboxgl.LngLat(item.lng, item.lat);
            let stars = "";
            for(let s = 0; s < item.rating; s++) {
                stars += '<img class="star-image" style="height:20px;width:20px;">';
            }
            const Popup_Content = '<div class="map-card__wrapper">'
            +'<div class="map-card__image-container">'
            +'<div class="map-card__image" style="background: url('+item.pictures[0].url+');">' +'</div>'
            +'</div>'
            +'<div class ="map-card__content-container ">'
            + '<div class ="map-card__title">'+item.name +'</div>'
            +'<p class="map-card__address">'+item.address1+'</p>'
            + '<div class ="map-card__review">'+stars +'</div>'
            + '<div class ="map-card__price-container">'+__("Flygbolag")+ ": "+ accounting.formatMoney(item.sales_prices[0])
            +'</div>'
            + '</div>';

            let marker = new mapboxgl.Marker()
                .setLngLat(myLatlng)
                .setPopup(new mapboxgl.Popup({ offset: 5 })
                .setHTML(Popup_Content))
                .addTo(map);
        });
    });
}

However, I am having trouble retrieving the value of

<div class ="map-card__title">
using the following approach:


$('.map-card__title').click(function(){
    alert();
})

There are no alert messages in the console when this code is executed. What could be the issue?

Any assistance you can provide would be greatly appreciated. Thank you.

Answer №1

The event listeners are being attached to elements that are dynamically generated.

In some cases, these elements may not have been created or added to the DOM when the $('selector').click(fn) function was executed.

To resolve this issue, it is recommended to delegate the event handling to a common parent of these elements, such as the main Map container or even the body element itself. By doing so, the body or Map can listen for click events on all child elements instead of attaching the listener directly to each individual element.

An example implementation would look like this:

$('body').on('click', '.children', function() {});

For more information on event delegation in jQuery, you can refer to the following resource:

https://learn.jquery.com/events/event-delegation/

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 steps should be taken in PHP to display a popup when the user input is found to be invalid?

I've been working on implementing a popup in PHP to show if the user enters an existing username, as per our teacher's requirement to use popUp instead of alert. I have set the visibility property of the popup to "Hidden" in CSS; <div class=&q ...

How can you create a function that can cater to two distinct scenarios?

My mind might need a little more effort, but let's imagine I have code that is 99% similar. What would be the most efficient way to construct a function for it? // This represents an express route, not the actual function being constructed // The goa ...

Scroll to the top on every Angular 5 route change

Currently, I am utilizing Angular 5 for my project. Within the dashboard interface, there are various sections with varying amounts of content. Some sections contain only a small amount of information, while others have large amounts of content. However, w ...

Tutorial on utilizing Puppeteer to interact with elements by specifying their x and y coordinates

I've been attempting to click a button on a webpage using x and y coordinates in puppeteer, but so far I've had no success. Here is the current method I am using. await page.mouse.click(x, y, {button: 'left'}) Despite not encountering ...

Delete the span element if the password requirements are satisfied

I am implementing password rules using span elements. I aim to dynamically remove each span that displays a rule once the input conditions are met. Currently, I have succeeded in removing the span related to the minimum length requirement but I am unsure h ...

Resolving issues with jQuery input values

I have been working on a form that allows users to choose an amount or specify another amount. When the user clicks on "other amount," it changes the displayed amount to $5. My goal is to make it so that when the user specifies an amount other than 5, it u ...

How to Validate Ionic 2 Radio Button Selections with TypeScript

Imagine having a list like the one shown below: <ion-list radio-group [(ngModel)]="autoManufacturers"> <ion-list-header> Auto Manufacturers </ion-list-header> <ion-item> <ion-label>Cord</ion-label> &l ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Attempting to invoke a TypeScript firebase function

I'm currently working on incorporating Firebase functions in my index.ts file: import * as functions from "firebase-functions"; export const helloWorld = functions.https.onRequest((request, response) => { functions.logger.info(" ...

coding with javascript and css

Essentially, I am trying to add padding specifically to the left side of this code snippet: if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("livesearch").innerHTML=xmlhttp.responseText; document.getElementById("live ...

ts1109: An error occurred as there was an expectation for an angular

I am encountering an error while creating a simple form with Angular using a reactive form. I'm puzzled as to why it's indicating that something is missing: Although I have created forms numerous times before, this is the first instance of such ...

The command "Npm Start Causes sleep is not accepted" just popped up

After cloning a React project from GitHub, I proceeded to run npm install, which successfully installed the node_modules folder. However, upon trying to run npm start, I encountered the following error: 'sleep' is not recognized as an internal or ...

What is the best way to introduce a time delay between two JavaScript functions?

Here is some JavaScript code that I am working with: clientData.reloadTable( "CreateCSV", "/create/file" ); $("#downloadFrame").attr("src","/download/download"); The first statement in the code above creates a CSV file on the disk. The second statement d ...

Is it possible to denote two "any" as the same thing in a TypeScript function signature?

Here is a function to extract items from an array based on a checker function: function extractItemsFromArray(array: any[], isItemToBeRemoved: (item: any) => boolean) { let removedItems = []; let i = array.length; while(i--) if(isItemToBeRemo ...

Fetch the information, insert following, and trigger a slide toggle

I am new to jQuery and I want to create a sliding table. The original table has 3 levels: <ul class="categories"> <li id="category1">1 element</li> //parentid=0 <li id="category2">2 element</li> //parentid=0 <ul> < ...

Encountering an issue with Node JS request and cheerio while parsing an HTML page

Greetings all, I am currently attempting to parse a website using Node.js (utilizing request and cheerio). The issue I am encountering is that I am trying to extract the href from the site, but I can only find it within the site's window. Unfortunatel ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...

ReactJS encountering issue with sending POST request, blocked by CORS preflight options

Every time I try to send a POST request to the server, it always responds with an unexpected OPTIONS. My login application built with React and Apollo is experiencing issues. Upon form submission, a mutation should be sent to the server via a POST request ...

What is the best way to retrieve data from ng-controller to use in the 'src' attribute of an <img> tag?

Check out this snippet of HTML: <div data-ng-controller="sampleCtrl" > <ul data-ng-repeat="item in sampleData"> <li class="message"> <img src="img-source" width="30" height="30"> <div class="message-text"> ...