Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc.

In Moogle Maps, you can use

.event.addListener(map, 'click', function()...
or switch 'click' with 'drag', 'mouseover', etc. Similarly, in jQuery, there are equivalents like 'click', 'keypress', etc.

Struggling with the idea of passing the trigger type as a variable. I have managed to create separate wrapper listeners easily, such as

function addClickListener(id, fn) {
    $(id).click(function() { fn(event); });
}      

// and

function addKeyPressListener(id, fn) {
    $(id).keypress(function() { fn(event); });
}

Having trouble implementing it with the below code snippet. Unsure how Google is able to pass a String like 'click' and execute a function. Possibly using eval? shudder

function addListener(id, type, fn) {
    typeFn = $.type;
    $(id).typeFn(function() { fn(event); });
}

Check out this example: http://jsfiddle.net/YCVVL/

Answer №1

You have the option to utilize the 'square bracket notation' in this scenario:

function addListener(id, type, fn) {
    $(id)[type](function() { fn(event); }); //< here
}

Alternatively, you can choose from one of the following methods:

$(id).on(type, function() { fn(event); });
$(id).bind(type, function() { fn(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

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

The issue of deleting the incorrect document ID in React Firebase

I'm currently facing an issue while trying to implement a delete operation on a Firebase database using Reactjs. The problem lies in my function that seems to be fetching the wrong id from Firebase. There's a button triggering the handleOpen fun ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

How to add vertical bars within ng-repeat in AngularJS

I attempted to retrieve values from an array variable using ng-repeat within unordered lists. Although the values are displaying correctly and everything is functioning properly, I added vertical bars after each value to represent sub-categories on my page ...

Run code after all images have been rendered in vuejs

Is there a way to execute code after all images have loaded, specifically needing to set the scroll in a specific position? Using nextTick() processes the code before the images are loaded. The mounted and created methods can't be used since the code ...

CSS: "Cutting-edge" design. In what way?

I am seeking to replicate a design similar to that of Fantastical's website (https://flexibits.com/fantastical), where the edge of a screenshot extends beyond the page boundary. As the user resizes the window, more of the screenshot becomes visible. A ...

Utilizing data attributes and JavaScript to dynamically assign a class to carousel navigation items

Hello there! I recently created a carousel and carousel navigation system using Bootstrap. I am now trying to figure out how to detect the value of 'data-slide-to' and then apply a specific style to the corresponding navigation item based on that ...

Is the JQuery ajax xhr fully completed before it begins?

Having a long script that can take a few minutes to execute, I decided to create a progress bar to display the current state. However, I encountered a problem where xhr evt.loaded/evt.total (30/30) returns 1 (100%) before the long script starts executing. ...

Conflict arising from duplicated directive names in AngularJS

Hey there, I've got a question for the experts. How can I prevent conflicts with directive names when using external modules? Right now, I'm utilizing the angular bootstrap module, but I also downloaded another module specifically for its carouse ...

Assist with JavaScript Programming

Can someone assist me in creating functionality for the "Show Picture" button to toggle the visibility of the picture when clicked? I've been trying to achieve this using an If/Else statement for a school project but have been struggling with it. Any ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

Unable to retrieve the value of a clicked button using jQuery

i am attempting to extract an array from checked buttons when a button is clicked. Although I can successfully retrieve the array, I am struggling to obtain the value of the clicked button. the code snippet below illustrates my attempt: $('.multiple& ...

Viewing all album titles simultaneously using the Flickr API

After trying a different approach due to lack of responses to my previous question, I am still facing the same issue. My code successfully retrieves all album names and corresponding photos from Flickr API, but it displays all album names at once followed ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

jQuery Ajax Load() causing screen to refresh unintentionally upon clicking

I am currently developing a web application that includes side menus. However, I am facing an issue with the functionality of these menus. Whenever I click on certain options, the entire page refreshes. For example, under my main menu "Planning the Engagem ...

Verifying user authorization for Microphone access prior to triggering event in React application

I have created a React component featuring a microphone button that operates as follows: OnMouseDown => Initiates audio recording by the user OnMouseUp => Ceases audio recording To elaborate, while the button is pressed down, the user can continue ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...