Ensure that the extension is only loaded once Angular has fully loaded

I am currently working on a Chrome extension that incorporates event listeners to elements within a page utilizing Angular 1.2.10. The following code snippet is an example of what I have:

window.addEventListener("load", (event) => {
var switchButton = document.getElementById('switch');
  switchButton.addEventListener('click', (event) => {
    reached = !reached;
  });
});

Although everything runs smoothly under normal circumstances, an error

Uncaught TypeError: Cannot read property 'addEventListener' of null
occurs if the page is loaded and tab is switched. It seems like the Angular application does not finish loading until switching back to the original tab, even though the load event still triggers.

Is there a way for me to delay the addition of the click listener to the 'switch' element until after the Angular app has completed populating the DOM?

Your assistance is greatly appreciated!

Answer №1

Develop a unique directive:

app.directive("handleClickEvent", function () {
    return {
        link: handleEvent
    };
    function handleEvent(scope,elem,attrs) {
        elem.on('click', (event) => {
          clicked = !clicked;
        });
    }
})

Next, apply that directive on the specific element:

<div id="toggle" handle-click-event>
</div>

The AngularJS compile service will automatically trigger the handleEvent function when it inserts the element into the DOM.

To gain further insights, visit AngularJS Developer Guide - Crafting Unique Directives.

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

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

Determine if a key begins with a specific string within an object and retrieve the corresponding value

If I have an object like this: let fruitSong = {'apple song':12, 'banana song': 24} Object.keys(fruitSong).forEach(e=>{ if(e.startsWith('apple')){ console.log(fruitSong[e]) } }) Is there a different meth ...

What is the reason behind JSLint's preference for x === "undefined" over typeof x == "undefined"?

I'm feeling lost when it comes to JSLint. Initially, my code checked if div:jqmData("me") was undefined in this way: if ( typeof el.jqmData("me") == "undefined" ? el.not(':jqmData(panel="main")').length > 0 : el.not(':jqm ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Is there a way to handle templates in AngularJS that is reminiscent of Handlebars?

Is there a way to handle an AngularJS template using a syntax similar to Handlebar? <script type="text/ng-template" id="mytemplate"> Name is {{name}} </script> I know how to retrieve the template using $templateCache.get('mytemplate&ap ...

Error encountered: [$rootScope:inprog] TriggerHandler causing issue with $apply - AngularJS

I'm attempting to simulate the click of a button when a key is pressed. I've implemented this functionality using the triggerHandler function, but it's resulting in the error mentioned above. I suspect there might be some kind of circular re ...

Expiration Date of Third-Party Cookies

I need help retrieving the expiration date of a third-party cookie programmatically using JavaScript. Even though I can see the expiry time in the browser's DevTools (refer to the screenshot at ), I am struggling to figure out how to access this infor ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

React component fails to re-render after state change

For the past two days, I've been struggling with this error and can't seem to fix it! I'm currently working on creating a weather app in React which utilizes the API. The app features a Bootstrap Navbar with a search option that allows user ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Error in JavaScript: A surprise anonymous System.register call occurred

Within Visual Studio 2015, there exists a TypeScript project featuring two distinct TypeScript files: foo.ts export class Foo { bar(): string { return "hello"; } } app.ts /// <reference path="foo.ts"/> import {Foo} from './f ...

Guide to highlighting rows in v-data-table with a click in Vuetify (version >= 2.0)

In my email management system, I utilize a v-data-table to organize emails. When a user clicks on a row, a popup displaying the email details appears. Desired Feature: I am looking to have the rows marked as "readed" (either bold or not bold) after th ...

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...

Anguar server encountered a startup issue and failed to initialize

My server.js file looks like this: var express = require('express'), api = require('./api'), app = express(); app .use(express.static('./public')) .use('./api', api) .get('*', ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Invoke another component to display within a React.js application

Click here to view the code snippet. I am facing an issue with my React components. I have component A that handles fetching and rendering a list, and I also have component B that accepts user input. How can I trigger component A from component B? It seem ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...