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

I'm encountering an issue with my API Key being undefined, despite having it saved in both an .env file and as a global variable

While attempting to retrieve information from an API, I encountered an issue where the key I was using was labeled as "undefined". However, after manually replacing {key=undefined} with the correct string in the network console, I was able to successfull ...

The jQuery form submission functionality fails to execute properly in the presence of a callback function

I have been on the hunt for a solution to this problem, but unfortunately I haven't been able to find one. The issue at hand is that when using the jQuery Submit function with a button and a callback function defined, it doesn't seem to work. Her ...

What is the best way to create a function that will return a Promise within an Express Route?

I am working with a business level database module named "db_location" that utilizes the node-fetch module to retrieve data from a remote server through REST API. **db_location.js** DB LOGIC const p_conf = require('../parse_config'); const db_ ...

Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle! Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The o ...

Unable to locate module '.next/server/font-manifest.json'

I'm encountering a frustrating issue while attempting to deploy my nextjs app with server rendering. The app was created using Azure Pipelines and then uploaded to a production server that runs on a Linux operating system. Below is the configuration ...

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

a function that is not returning a boolean value, but rather returning

There seems to be a simple thing I'm missing here, but for the life of me, I can't figure out why the function below is returning undefined. var isOrphanEan = function isOrphanEan (ean) { Products.findOne({ 'ean': ean }, func ...

In order to achieve a sliding effect for the second div, it can be programmed to

Currently, I am working on implementing hide and show functionality in my project. However, I have come across a bug in my code that I need assistance with. When clicking on the first div element, the content opens from bottom to top instead of the desired ...

Leverage recursion for code optimization

I'm currently working on optimizing a function that retrieves JSON data stored in localStorage using dot notation. The get() function provided below is functional, but it feels verbose and limited in its current state. I believe there's room for ...

Manipulating elements with JavaScript to remove them, while ensuring that the empty space is automatically filled

Recently, I decided to enhance my understanding of JavaScript by experimenting with it on various websites. My goal was to use JavaScript to remove the right bar from a webpage and have the remaining body text automatically fill in the space left behind. ...

Unleashing the Power: Crafting Impeccable For Loops

After running the select query in the "get-employee.php" page, I obtained the answer for this page. Then, I returned the data to the previous page (home.php). On this page, I added a for loop in JavaScript before the tag with the class "col-md-3". Within t ...

I was disappointed by the lackluster performance of the DataTable in CodeIgniter; it did not

I recently started using CodeIgniter and I'm having trouble getting the dataTable to work. Here's a snippet of my page: <table class="table table-striped table-bordered table-hover dataTables_default" id="dataTables-example"> ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Using Node Express.js to access variables from routes declared in separate files

Currently, I am in the process of developing a website with numerous routes. Initially, all the routes were consolidated into one file... In order to enhance clarity, I made the decision to create separate files for each route using the Router module. For ...

The conversion from CSV to JSON using the parse function results in an inaccurate

I am having trouble converting a CSV file to JSON format. Even though I try to convert it, the resulting JSON is not valid. Here is an example of my CSV data: "timestamp","firstName","lastName","range","sName","location" "2019/03/08 12:53:47 pm GMT-4","H ...

Tips for applying a custom design to your MUI V5 styled component

How do I customize the style of a button component in MUI V5? I've been trying to combine old methods with the new version, but it's not working as expected. import { Button } from "@mui/material"; import { styled } from "@mui/mate ...

Navigating with React Router using server-side routing in the web browser

I'm currently developing a web application that utilizes react on the client side and express on the server side. For routing the client pages, I've been using react-router (link). Initially, I had success using hashHistory, but now I want to ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

Distributing utility functions universally throughout the entire React application

Is there a way to create global functions in React that can be imported into one file and shared across all pages? Currently, I have to import helper.tsx into each individual file where I want to use them. For example, the helper.tsx file exports functio ...