The Power of 'this' in JavaScript Object Literal

Trying to manage multiple modals on an HTML page using a JavaScript object literal. Unfortunately, encountering an error when attempting to display the modal by clicking a button.

Uncaught TypeError: this.showModal is not a function
    at HTMLButtonElement.modalBtns.(anonymous function).onclick (file:///C:/dj-sites/ux_bee/js/base.js:63:22)

Suspecting that the issue lies in the "this" keyword, which seems to be referencing the button instead of the object literal. Need to figure out how to resolve this.

var myModalObj = {
    findAncestor: function(el, cls) {
        while ((el = el.parentElement) && !el.classList.contains(cls));
        return el;
    },
    showModal: function(btn){
        var modal_id = btn.getAttribute('data-modal')
        var modal = document.getElementById(modal_id);
        modal.style.display = "block";
    },
    closeModal: function (btn){
        var modal = this.findAncestor(btn, 'modal')
        modal.style.display = "none";
    },
    init: function(){
        var modalBtns = document.getElementsByClassName('my-modal-btn');
        for(var i = 0; i < modalBtns.length; i++) {
            var btn_modal = modalBtns[i];
            modalBtns[i].onclick = function() {
                this.showModal(btn_modal);
            }
        }

        var closeBtns = document.getElementsByClassName('modal-close');
        for(var i = 0; i < closeBtns.length; i++) {
            var btn_close = closeBtns[i];
            closeBtns[i].onclick = function() {
                this.closeModal(btn_close);
            }
        }
    }
}
myModalObj.init()

Answer №1

To simplify things, just substitute all occurrences of this with myModalObj, like this.

var myModalObj = {
    findAncestor: function(el, cls) {
        while ((el = el.parentElement) && !el.classList.contains(cls));
        return el;
    },
    showModal: function(btn){
        var modal_id = btn.getAttribute('data-modal')
        var modal = document.getElementById(modal_id);
        modal.style.display = "block";
    },
    closeModal: function (btn){
        var modal = myModalObj.findAncestor(btn, 'modal')
        modal.style.display = "none";
    },
    init: function(){
        var modalBtns = document.getElementsByClassName('my-modal-btn');
        for(var i = 0; i < modalBtns.length; i++) {
            var btn_modal = modalBtns[i];
            modalBtns[i].onclick = function() {
                myModalObj.showModal(btn_modal);
            }
        }

        var closeBtns = document.getElementsByClassName('modal-close');
        for(var i = 0; i < closeBtns.length; i++) {
            var btn_close = closeBtns[i];
            closeBtns[i].onclick = function() {
                myModalObj.closeModal(btn_close);
            }
        }
    }
}
myModalObj.init()

The need for this adjustment arises because the function being called is exclusively kept in myModalObj, making it the sole method to invoke it.

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 am facing an issue with my sequelize model where the "before create" functionality is not

Having issues with my before create hook in Sequelize model I've set up a template, but my before create hook doesn't seem to be working and I'm struggling to figure out why. async createUser(req,res){ const { name,email,login,password ...

AJAX request failed to elicit a response

Recently, I've been facing an issue with my AJAX call to the API. Previously, it was functioning correctly and returning a response JSON. However, now I am unable to retrieve any JSON object. When using Mozilla, no error is shown but the response JSON ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

Having trouble with Angular2's Maximum Call Stack Exceeded error when trying to display images?

I am facing an issue in my Angular2 application where I am trying to display an image in Uint8Array format. The problem arises when the image size exceeds ~300Kb, resulting in a 'Maximum Call Stack Exceeded' error. Currently, I have been able to ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

What is a clever way to monitor the completion of a forEach loop using promises?

I'm new to promises and I'm attempting to use them for the first time. After the completion of the forEach loop, I want to call another function for additional processing. However, when using forEach, the function insertIDBEvents is only printed ...

What is the best way to place content in a single div without it being divided into several separate boxes

Here is my code snippet: <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"&g ...

Change numbers into a comma-separated style containing two decimal points using javascript

I have been working on a JavaScript function to convert numbers into a comma-separated format with two decimal places: Here is my current code snippet: Number(parseFloat(n).toFixed(2)).toLocaleString('en'); The issue with this code is that it ...

Learn the process of updating a specific section of a Facebook share link using AJAX dynamically

Here's an interesting scenario I'm dealing with. I'm trying to create a modification to the Facebook share button link where a portion of the link is replaced by a user ID number. This way, when someone clicks on the shared link, it will dir ...

I'm having trouble getting the specific object I need to be returned

I'm currently working with NodeJS and using some JS promises in an attempt to interact with a CMS via a specific web application. The issue I'm facing is when I try to fetch data from the CMS API. While I can successfully log the data to the cons ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Verify the middleware is connected to the express endpoint during the unit test

How can I verify that the middleware is properly attached to the route in my unit test below? The server .. var express = require('express'); var http = require('http'); var app = express(); var server = http.createServer(app); var P ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

Interacting with HTML elements in Java programming

I am facing a challenging situation that requires some brainstorming. I would greatly appreciate any advice or guidance in the right direction. My goal is to incorporate a Google Map into my Java Swing project, with the map being specified as a URL wit ...

@mui/x-date-pickers styling for the DatePicker component

Despite numerous attempts, I have been unsuccessful in styling the @mui/x-date-pickers <DatePicker/> component. I've experimented with various methods such as sx={{}}, style={{}}, makeStyles(), .css with the !important rule, renderInput={(param ...

Nested function and the process of breaking out of the parent function

Is it possible to exit out of the main/parent function when I am in a function that was called from inside another function? For example: function(firstFunction(){ //stuff secondFunction() // code continuation if second function doesn't ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

React Component State in JavaScript is a crucial aspect of building

What happens when the expression [...Array(totalStars)] is used within a React Component? Is the result an array with a length of 5, and what are the specific elements in this array? We appreciate your response. class StarRating extends Component { ...

Transforming the date format in VUE-JSON-EXCEL

Is there a way to change the date format for the VUE-JSON-EXCEL library? When I click the generate excel button, the date format displayed in the excel is "2022-06-10T18:18:34.000Z" instead of "10/6/2022 18:18:34" I have tried using moment.js but it is n ...