Identifying user interaction with a dynamic drop-down menu using extension javascript

I'm currently working on detecting a click event on a list element using JavaScript, with a slight complication. The list element is located within a dropdown menu from a search bar on Quora. www.quora.com - Specifically, I am interested in identifying when a user clicks the "add question" button and triggers the popup box to appear.

The popup box contains additional div elements that are either hidden or dynamically generated. The HTML structure for the list items is as follows:

<li class="addquestionitem" id="__w2_FWrLuSU_list_item_11">

When hovering over this particular list item, its class changes to:

<li class="addquestionitem selected" id="__w2_FWrLuSU_list_item_11">

Currently, my code snippet looks like this:

$("li[class='addquestionitem selected']").click(function() {
    $(document).ready(function(){
        alert('this link has been clicked');
        $("div[id$=_publish_checkboxes]").append(element);
    }

However, even the alert message is not being displayed. Any suggestions?

Update None of the suggested solutions below have proven successful. I also tried testing it with the "create board" button on the Quora homepage, which triggers a similar CSS-based popup. It worked in that scenario. Here's the selector I used:

$("a[class='add_content_link action_button icon_action_button']")

I fail to see why it wouldn't work with the "add question" button in a comparable context.

Update 2 Here's the content of the manifest file:

{
    "name": "A browser action with a popup that changes the page color.",
    "version": "1.0",
    "manifest_version": 2,
    "browser_action": {
        "default_title": "Set this page's color.",
        "default_icon": "icon.png"
    },
    "permissions": [
        "tabs", "http://www.quora.com/*"
    ],
    "background": {
        "page": "popup.html"
    },
    "content_scripts":[
        {
            "matches": ["http://www.quora.com/*"],
            "js": ["jquery.js", "read_in_array.js", "add.js", "popup.js"]
        }
    ]
}

Answer №1

Do you have any recommendations?

In order to improve your code, it is suggested that you wrap the $.ready function around all other functions. Additionally, since the drop-down menu is likely to be dynamically generated, using delegated events is recommended. Your class selector seems unusual, and it may be beneficial to remove the selected class altogether.

$(document).ready(function(){
    $(document).on("click", "li.addquestionitem", function() {
        alert('this link has been clicked');
        $("div[id$=_publish_checkboxes]").append(element);
    });
});

Answer №2

It's possible that the .click() event listener is not triggering because it's waiting for $(document).ready(), which has already been fired before the click action occurs.

You can attempt the following modification:

$(document).ready(function(){
    $("li[class='addquestionitem selected']").click(function() {
        alert('The link has been clicked');
        $("div[id$=_publish_checkboxes]").append(element);
    });
});

Answer №3

This situation appears to call for delegation either to the document element or the parent container. By binding the click function right away, it may not work if the li does not have the selected class. To capture clicks via the parent element, you can try the following approach:

$(document).ready(function(){
    $("#__w2_FWrLuSU_results_list").on("click", "li.addquestionitem", function()
    {
        alert('The link has been clicked');
        $("div[id$=_publish_checkboxes]").append(element);
    });
}

Answer №4

Here's a suggestion;

$(document).ready(function(){
    $('.addquestionitem').on('click', function(){
        alert('this link has been clicked');
        $("div[id$=_publish_checkboxes]").append(element);
    });
});

Answer №5

Upon inspecting the event listners for that specific element (select the element and refer to the Event Listeners in the Elements panel, focusing on an event targeting that element and its action during the mousedown) it becomes clear that they are not utilizing click, but instead mousedown. It appears that their event is triggered before yours, potentially halting bubbling. To rectify this issue, change your event to mousedown, and it should work as intended. Additionally, please note that this element may not be readily available immediately after DOM ready (this aspect is uncertain). You might need to implement a setTimeout function to continuously check for the element's presence, leverage mutation observers, or utilize a method tailored to the site's requirements.

// wait for the element to exist then do your thing
var wait = function() {
    if ($("li.addquestionitem").length > 0) {
        console.debug('found it');
        $('.addquestionitem').live('mousedown', function() {
            alert('this link has been clicked');
            $("div[id$=_publish_checkboxes]").append(element);
        });
    } else {
        setTimeout(waiting, 500);
    }
}
wait();

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

The load event in React's iframe is failing to fire after the src attribute is modified using state

In the process of creating a registration form for a React application, we encountered the need to incorporate an HTML legal agreement as an iframe. This legal document is available in various languages, one of which can be selected using a drop-down menu; ...

What is the best way to arrange div elements in this particular manner using CSS?

Wanting to create a specific layout for my website by positioning some divs in a unique way and adding content to them, I have been focusing on responsive design. I am wondering if it is possible to position these divs while ensuring responsiveness. The de ...

The transition animations on a mouseover accordion effect are not smooth

Looking to set up a simple website for a project that fetches data from a server using AJAX and displays it as depicted in the image? The issue isn't with JavaScript but rather with pure HTML+CSS. To view this page on jsfiddle, you can click here. Al ...

What is the best way to efficiently filter an array in React without ending up with an empty result?

I am currently facing an issue with filtering an array of users based on an input field. The problem arises when characters are deleted, as the array does not update in real-time and remains the same as the last search query. I suspect this is happening be ...

FadeOut Television static on Canvas after a period of inactivity

Is there a way to smoothly fade out the TV noise after a specific timeout period? I found this code snippet on Stack Overflow that seems to address a similar issue: var canvas = document.getElementById('canvas'), ctx = canvas.getContext( ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Having trouble with positioning elements next to each other using Bootstrap4 list-inline

I am currently tackling the challenge of building a "Quote Machine" as part of my freeCodeCamp projects. My goal is to create a list that contains three list items functioning as buttons, lined up next to each other using the Bootstrap class "in-line." How ...

Tips for validating a form with the assistance of jQuery

While there are multiple answers out there for this particular question, I am specifically interested in validating an entire form with dynamic input fields sourced from a database similar to Google Forms. HTML <div class="rs_card"><spa ...

When using Vue.js, binding may not function properly if it is updated using jQuery

Link to JsFiddle Below is the HTML code: <div id="testVue"> <input id="test" v-model="testModel"/> <button @click="clickMe()">Click me</button> <button @click="showValue()">Show value</button> </div& ...

Unable to process JSON array

One issue I'm facing is with an 'onload' handler for my web page. The javascript function 'handleLoad()' that it calls has suddenly stopped working, specifically not being invoked after attempting to pass the output of json_encode ...

Proper method of defining an action in Vuex

Do you think it's sufficient to create vuex-actions as simple as a1, without chaining then/catch calls? Or should I always go with creating Promises as in a2 (and also adding a reject branch)? Appreciate your insights... import Vue from 'vue& ...

Obtaining the response object for the web browser

Greetings! I currently have a function within router.js in NODEJS : const authenticateUser = (req, res, next) => { //something }; Whenever my application is live, this function is triggered. I am looking for a way to examine the response object. Is ...

Ways to extract data from a JSON file using jQuery and assign them as text values?

I have a data table that I serialize into JSON and then parse in my view using jQuery to access the values. However, when I use document.getElementById('Name').value = UserInfo.Name; the value of Userinfo.Name = null, I'm having trouble ...

Can someone explain how the "class*=" selector functions in Django/Javascript/SQLite3? I'm curious about its purpose and how it operates

Embarking on a web development project in Django involving a database of ancient Greek and Latin texts previously worked on by others. Although I have some basic knowledge of Django and Javascript, there are still areas where I require clarification. Exam ...

Transforming and categorizing a string array into a tree structure

Array showing different included elements: var exampeInclude= [ "Product", "Group", "Product.Tax", "Product.ProductUnit", "Product.Variant.Original", "Product.Variant.Original.Tax", "Product.Variant.Original.ProductUnit" ]; Desired hierarch ...

What are the distinctions between uploading a standard file and generating thumbnails of images in MVC?

Hello, I am facing some confusion regarding file uploading. Can someone please explain to me the difference between a normal file upload and creating a thumbnail for an image and saving that path in a database? I have checked the paths for both normal and ...

Displaying a list of JSON data in HTML using Angular.js is a breeze

I am attempting to create an HTML list displaying the id fields of game objects from a json file. However, it is not appearing in my user interface. I am unsure why it is not rendering properly. ---core.js--- var gameapp = angular.module('gameapp&ap ...

Show drawer when modal is open in React Native

Currently, I am working on a project in react-native and facing an issue where the modal is appearing over the drawer navigator. Despite trying to adjust the zIndex property, it has not been effective. Details of my modal: <Modal visible={isVisible} ...

Don't forget to retain the checkboxes that were chosen in the

I am looking for a solution to a specific scenario. When I open a modal box and check some checkboxes, I want those same checkboxes to be selected the next time I open it. Below is an example of my code. Main Controller modal function function openModa ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...