Toggle a MutationObserver using a button to stop and start monitoring for changes

Is there a way to connect a MutationObserver and disconnect it using the same button? I know how to do each separately, but I want to use just one button. How can I achieve this? Apologies for my poor English.


var target = document.getElementsByClassName('message')[0];

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.info("EVENT TRIGGERED");
  });
});

var config = {
  attributes: true,
  childList: true,
  characterData: true
};

function disconnect() {
  observer.disconnect();
}

function observe() {
  observer.observe(target, config);
}

// Simulate change
refreshIntervalId = setInterval(function() {
  document.getElementsByClassName('message')[0].innerHTML = Math.random().toString(36).substring(2, 15);
}, 1000);

Answer №1

To effectively manage your observer state, consider creating a separate variable (for example, isObserving). Update this variable to true within your obs() function, set it to false in the dis() function, and then utilize a toggleObs() function with your button.

function toggleObs() {
  if(isObserving) {
    dis();
  } else {
    obs();
  }
}

Answer №2

Observable objects do not have a built-in property to indicate whether they are currently being observed or not. As a result, it is necessary to manually keep track of this information. Refer to the following example for clarification: https://stackblitz.com/edit/js-8mk72n

let isObserving = false;
window.toggleObserve = function() {
  isObserving = !isObserving;
  isObserving ? window.obs() : window.dis();
}

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

Directive's ng-click function fails to execute

This directive contains a function that should be executed when clicked. ebApp.directive('monthDir', function () { return { restrict: 'E', templateUrl: 'htmlFiles/monthDirective.html', transclu ...

Activate a click event on an element using Simple HTML DOM

I need assistance in triggering a click on the element below and then retrieving its innertext. <a class="btn btn-sm btn-default" href="javascript:;" onClick="score(238953,this)">Show result</a> Once the "onClick" event is triggered, the elem ...

Leveraging ng-model with expressions in ng-repeat in AngularJS.Would you

Currently, I am tasked with creating a form for a multilanguage content management system using angularJS. The language list has been defined within the angular scope as follows: $scope.languages = [ {id:0,'name':'English'}, {id:1, ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

How can you achieve the effect of "hovering over an image to automatically start playing a muted video within the image itself"?

[![enter image description here][1]][1]I am working with WordPress and Elementor, and I want to create a hover effect where an image triggers a muted video to play within the image area on mouseover. The video should stop playing when the mouse is not hove ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

jquery and radio button technology

I am attempting to create a basic function using jquery, but it is not functioning properly. Here is the radio button in question: <input type="radio" id="price" name="shipping" class="styled" /> In the head section of my HTML, I have included the ...

Execute a function once the router-view in the App.vue component has been refreshed following a route alteration triggered by vue-router

Is there a way to trigger a function after the contents in <router-view/> within App.vue have been updated following a route change? I attempted using the updated() lifecycle hook, but the function is not being executed. Interestingly, the function ...

react-navigation hook for navigating

Currently, I am utilizing the react-navigation hook and instead of repeating the hook in various components, my goal is to pass navigation as a prop. const navigation = useNavigation(); ... <MyButton resetLocation={resetLocation} navigation= ...

What are the ways to change a PDF file or web address into a DOCX document using NodeJS?

I've been doing some research on converting URLs to DOCx or PDF to DOCx in NodeJS, but I haven't found a proper solution yet. I tried reaching out to PhantomJS, but it only converts URLs to PDF. Do you have any idea if PhantomJS can convert to D ...

Dealing with multiple submit buttons in a form with Angular JS: best practices

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form an ...

I am attempting to secure a webpage with a password using JavaScript

I've been working on adding password protection to my webpage at , with the goal of allowing users to enter the password once per session. However, I've encountered an issue: if a user cancels out of the initial prompt or enters the wrong passwor ...

Having trouble locating the correct JSON array syntax for Highcharts

Hey there! I'm currently facing a bit of a challenge while trying to set up a JSON array using PHP and integrate it into Highcharts. Currently, I am creating the array in this manner: $stack[] = array($commname => $countit); $stack = json_encode( ...

React Login Redirect

I am struggling to implement a redirect in my React project login. Despite researching online and finding solutions using routers, I have been unsuccessful in adding it to my code correctly. Here is my code - how can I effectively implement the router? Ap ...

Initial position of jQuery slider

A while back, I came across some slider code on a website and copied it. Unfortunately, I can't seem to locate the source now. Here is the code snippet: slides.min.jquery.js $(function(){ $('#slides').slides({ preload: true, ...

Bringing in two JavaScript files with identical names

Recently, I encountered a challenging situation. I am working with material-ui and nextjs, both of which have a module called Link that is essential for my project. import { Link } from '@material-ui/core'; However, this setup is causing compil ...

Using javascript to extract values from nested JSON structures without prior key knowledge

My JSON data is structured as follows: {"sensors": {"-KqYN_VeXCh8CZQFRusI": {"bathroom_temp": 16, "date": "02/08/2017", "fridge_level": 8, "kitchen_temp": 18, "living_temp": 17, ...

AngularJS $HTTP service is a built-in service that makes

I am facing an issue with pulling the list of current streams from the API and iterating that information with AngularJS. I have tried inputting the JSON data directly into the js file, and it works fine with Angular. However, when I use an http request as ...

Implementing AngularJS to display different divs according to the selected value

I am attempting to utilize the value of an HTML select element to toggle the visibility of specific div tags using AngularJS. Below is the code snippet I have been working with: <body ng-app="kiosk" id="ng-app" > <div class="page" ng-controll ...

Utilize only certain JSON properties within JavaScript

I have access to an array of JSON objects. [ { Id: "1", StartNo: "1", ChipNo: "0", CategoryId: "0", Wave: "0", Club: "", FirstName: "Lotta", LastName: "Svenström", FullName: "Lotta Svenström", ZipCode: "24231" }, {...} ] My goal is to create a new data ...