Learning the process of connecting functions to events

    // param {id:'buttonId', action : function(event[,param1, param2] ){}, behavior:function(event[,param1, param2] ){} }
    CustomButton = function(parameters) {
         var buttonElement = document.getElementById(parameters.id);
         // how can I utilize the passed action function from 
         // parameters and include additional parameters like function(event[,param1,param2]) 
         buttonElement.onclick = parameters.action;
    }

I am currently working on creating a customized toggle button that functions as a link. I would like to be able to add events as described above but I am struggling with implementing them for the buttons in order to use code similar to the example below:

new CustomButton({id: 'button1', "action" :  function(event, parameter1, parameter2){ 
        //function body 
    }
});

Answer №1

If I were to tackle this task, here's how I would approach it:

<a href="foo.html" id="toggle1">Toggle</a>


var ToggleButton = function(params) {
    var btn  = document.getElementById(params.id);
    var evt  = 'on' + params.evt;
    btn[evt] = params.action;    
    return;
}

ToggleButton({
    id:      'toggle1',
    evt:     'click',
    action:  function(evt){
        var clickedElement = this;
        alert('The href value of the element is '+ clickedElement.getAttribute('href'));

        // To prevent the browser from following the href link
        var e = evt || window.event;
        e.preventDefault();
    }
});

Answer №2

Here are the steps you can take:

CreateToggleButton = function( config) {
      var control = document.getElementById( config.id);
      if ( control) {
         control.onclick = config.handler;
      }
} 

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

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Error message: Metro bundler is unable to access the properties of an undefined object (specifically, 'transformFile')

Having encountered a problem after updating my project to expo SDK 43, I have experimented with different LTS node versions (14.8.1, 16.1.3, and 17.0.1) without success. Interestingly, my colleagues using Macs with Intel chipsets do not face this issue, le ...

Restricting JSON output using date and time values within the JSON object

Currently, I'm in the process of creating a play data reporting tool specifically designed for a radio station. The main concept involves retrieving play history from the playout software's API and manually adding tracks that were played outside ...

Retrieving HTML content using scriptJS

Currently utilizing VueJS and encountering an issue after compiling code in production mode. I have one index.html file and several assets that are being uploaded to the cloud. The challenge lies in the fact that the client is not accepting the HTML file ...

Error with review score in material-ui for react.js

There is an issue with my code where the ratings from different sets are not behaving independently. When a rating in one set is clicked, only the first set of ratings changes, suggesting that there is a connection between all the sets. The root cause of ...

Tips for effectively utilizing foreach loops in JQuery

I've encountered an issue while displaying a list of data in a table using Smarty templates and foreach loops. I'm trying to make each line clickable to show new data below it, but currently, this functionality only works for the first line. Is t ...

What is the recommended way to configure the build.gradle file for the app build process?

I am currently working on building the app using the command provided below. /android gradlew assembleRelease My main query at this point is whether it is necessary to eliminate the debug of signingConfigs and debug of buildTypes when transitioning into r ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

Firebase Operation Not Supported Error in next.js (auth/operation-not-supported-in-this-environment)

After successfully deploying a Next.js app hosted on Vercel with Firebase authentication that functions properly for users, I encountered a mysterious error during the "npm run build" phase: FirebaseError: Firebase: Error (auth/operation-not-supported-in ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...

In my development environment, the page does not have scroll functionality, but in the production environment, it is scrollable

Whenever I open a table or any other element with overflowing content, I encounter an issue with the scrolling bar. Even though the CSS includes overflow-y: scroll;, the scroll bar on the right remains in gray and does not allow me to scroll down when the ...

Using the <noscript> tag for an individual element or a comparable alternative

So, I have a link labeled "Impressum" that when clicked, opens up the Impressum section. <a data-open="something">Impressum</a> <div class="reveal" id="something" data-reveal> <img src="images/reverseLogo.png"> <h1>Imp ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

Is it possible to send props to a component within the render method?

I have a button component in my render method (DownloadReportsButton) that will trigger a modal onClick and perform an API call. The logic for the modal and the API call have already been moved to the button component, but how do I pass my data (an array ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

What is the best way to define a variable within a function?

Here's a function designed to verify if the username has admin privileges: module.exports = { checkAdmin: function(username){ var _this = this; var admin = null; sql.execute(sql.format('SELECT * FROM tbl_admins'), (err, result, fields ...

Guide on how to use JavaScript to swipe through loaded epub files in both lateral directions

Hello everyone, I have a question about implementing swipe functionality on a loaded epub using JavaScript. I successfully loaded the epub into a div and now I need to enable swipe left and right gestures on that div. I found a jQuery script that should a ...