javascript event-driven class

I'm facing a challenge in creating a class with chained functions, and I could really use some assistance. Currently, this is what I have:

robin = new batman("myiv");
var batman = (function() {
    var me = this;
    function batman(id){
        me._id=id;
        document.getElementById(id).addEventListener('mousemove', me.mouseMoving.bind(me),true);
    }
    this.mouseMoving = function(){
        document.getElementById(me._id).style.background="orange";
    }

    return batman;
}

This pseudo code outlines my desired outcome. Essentially, I want to input the ID of an element in my HTML and be able to chain functions like onclick etc., allowing the specified code inside those functions to execute – for example, changing background colors.

Is this achievable?

superman("mydiv"){
    .onmouseover(){
        document.getElementById(the_id).style.background="#ffffff";
    },
    .onmouseout(){
        document.getElementById(the_id).style.background="#000000";
    },
    etc...
}

Edit: included missing code: "return batman;"

Answer №1

To utilize method chaining, simply return the current object by using this keyword

var YourClass = function () {
  this.items = [];
  this.push = function (item) {
    if (arguments) {
      this.items.push(item);
    }
    return this;
  }
  this.count = function () {
    return this.items.length;
  }
}

var obj = new YourClass();
obj.push(1).push(1);
console.log(obj.count())

See a working example at:

https://stackblitz.com/edit/method-chaining-example?file=index.js

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

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

Is the ctx.arc method in Javascript able to determine the vertices based on the pixel size and radius?

When working with Javascript's Canvas, you have the option to draw a circle easily using the ctx.arc method. I'm curious, does the arc function automatically calculate the optimal number of vertices needed to draw a circle in order to achieve the ...

Building a conditional statement in React based on the URL path: A beginner's guide

I want to incorporate a transparent menu specifically on the homepage. How should I go about this? I've established a constant named isHomePage and now I need to set a URL (the index.tsx) to define this constant. function MyApp({ Component, pageProps ...

Is there a way to change the entire background color of my popover?

Hi there! My issue is that the arrow in my popover isn't changing color and is still showing up as white. Here is the current code: http://jsfiddle.net/GZSH6/19/ Here is the CSS code: .popover { background: #BE7979; color: white; borde ...

Is there a way to dynamically convert a css rule like "select::-ms-expand" to JavaScript?

Looking for assistance with implementing the following code snippet in JavaScript: "$('select').css('-moz-appearance','none');". I've tried searching on Google for solutions, but haven't been successful. Any tips or ...

How to choose elements using jQuery according to their CSS properties?

Seeking a solution to a unique challenge I've encountered. The website I frequent has found a way to bypass my uBlock extension by using a script that generates random element classes, such as: <div class="lcelqilne1471483619510ttupv"></div& ...

Encountering a problem with npm reading dependencies

I decided to kickstart a new Node application by following a tutorial and creating a package.json file. Below is the content of my json file: { "name": "Dashboard", "version": "0.0.0", "description": "Client-A Dashboard", "dependencies": { ...

Using jQuery, adjust the width of child elements within a container by applying dynamic CSS styling

I am attempting to dynamically set the width of several child elements using jQuery. Here is what I am trying to achieve: Obtain the count of the desired containers (since there will be multiple instances of the .steps-container class in the DOM) Iterate ...

Tips for showcasing personalized validation alerts with jQuery in the HTML5 format?

One of the Javascript functions I designed is for validating file extensions before uploading: function validateFileExtension(field, extensions){ file_extension = field.val().split('.').pop().toLowerCase(); if ($.inArray(file_extension,exten ...

How can I repeatedly trigger an eventListener in JavaScript?

I'm currently facing an issue with calling the event listener for all 4 progress bars on my page. The problem is that it's only working on the first progress bar. I cloned the div with the id of 'mycontainer' using a for loop, but the e ...

Fetching data from Page 1 and passing it to Page 2 using Javascript

I'm currently experiencing an issue with my AJAX function where it needs to transfer a value from page 1 to page 2 for storage. Let's start with the AJAX function on page one: top.location.href = 'http://www.something.com/redirect.php?emai ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

What are the steps to customize the date pipe in Angular?

Encountered the InvalidPipeArgument issue with Safari for date/time format, but managed to resolve it by following the solution provided in this Stack Overflow thread. Currently using: <mat-cell *cdkCellDef="let payroll" fxFlex="20%"> {{payroll.tim ...

Tips for transferring POST body data to a different route without losing any information

Assuming I have the following route: app.post('/category',function(req,res){ res.redirect('/category/item'); }) In this scenario, the user will submit data to the '/category' route and then automatically be redirected ...

Struggling to get Axios working in Node despite having it properly installed

I am encountering an issue with my Jasmine test that involves HTTP requests. Despite having Axios installed using the command npm install axios --save, I keep getting the error message axios is not defined. var request = require('axios'); var co ...

Tips for attaching event listeners to custom elements

Let's suppose I create a Vue component called Checkbox.vue that contains the following code. <template> <div class="checkbox"> <input id="checkbox" type="checkbox"> <label for="checkbox">Label</label> ...

Having trouble getting a Three.js invisible plane to work correctly with raycaster.intersectObject?

I've been experimenting with creating draggable objects similar to this interesting example: The array objectMoverLines contains the objects that should be draggable. To incorporate a plane into my scene, I utilized the following code: plane = new ...

JavaScript - Dynamic rotation algorithm

I recently developed a piece of code to manage object rotation in a THREE.js environment. Although the issue is not specific to 3D. My goal is to have my object (referred to as 'this') rotate by 0.25 radians each time a function is called, until ...

What mistakes did I make in my Ajax code?

My aim is to dynamically add items to my listbox when a button is clicked, and then retrieve the value of the added item in the listbox using ajax. Below is the code I have tried: $('#right').click(function () { alert("Start process"); ...

Adding an image to a select option in HTML using PHP - A step-by-step guide

How can I include an image within a select option using PHP in HTML? The image needs to be retrieved from a database first. echo '<option value='.$ifet['productimage'].'><img src='.$ifet['productimage'].&a ...