Access nested JavaScript functions from HTML

2

I have the following JS code and I try to access the functions start() and stop() from a div with the events onmouseover="" and onmouseout="" :

NewsScroller = function(id, speed) {

  this.start = function() {
    _timer = window.setInterval(self.doScroll, this.scrollSpeed);
  };

  this.stop = function() {
    if (_timer) window.clearInterval(_timer);
  };
};

var scroll = new NewsScroller('marquesina', 10);
<div id="marquesina" onmouseover="scroll.stop();" onmouseout="scroll.start();">
  Soy una Marquesina
</div>

But when executing it tells me that start and stop are not functions.

How else can I have the nested functions called to work?

    
asked by Luis-Ortiz 14.02.2018 в 00:26
source

1 answer

1

The problem is not that the functions start and stop are wrongly called, the problem is that scroll is the name of a method of window . And within the context of onmouseover and onmouseout , scroll will refer to the scroll of the window and not your variable scroll .

A quick solution would be to rename your variable, for example to miScroll :

NewsScroller = function(id, speed) {
  
  this.start = function() {
    console.log("START");
  };

  this.stop = function() {
    console.log("STOP");
  };
  
};

var miScroll = new NewsScroller('marquesina', 10);
<div id="marquesina" onmouseover="miScroll.stop()" onmouseout="miScroll.start()">
  Soy una Marquesina
</div>
    
answered by 14.02.2018 в 05:34