A
A
Anton2014-10-19 10:50:11
JavaScript
Anton, 2014-10-19 10:50:11

How to call an object method that processes an element that does not yet exist?

Let's say I need to process elements in a fancybox container (which appears when a button is clicked).
For example, let's show "name" when hovering over a 'div' element in a fancybox that appears.

doesn't work like this construct:

var obj = {
show: function() {
        $('body div').mouseover(function() {
                $('.name', $(this)).show();
        } );
    }
}
$(function( {
    obj.show();
});

like this:
var obj = {
show: function() {
        $('body').on('mouseover', 'div',
            function() {
                $('.name', $(this)).show();
            }
        );
    }
}
$(function(){
    obj.show();
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Petrov, 2014-10-19
Pochachalov @nicenice

Why are you tracking the event on body ? Since you are using the ascent, do it right, not half way.
And if you refer to body , then like this $(document.body) .

var obj = {
  show: function () {
    $(document).on('mouseover', 'div', function () {
      //this — это div
      ...
    });
  }
}
obj.show();

A
Anton, 2014-10-19
Pochachalov

This build works:

$(function(){
    $('body').on('mouseover', 'div',
            function() {
                $('.name', $(this)).show();
            }
        );
});

But I need to call it through an object method...

D
Dmitry Ermolaev, 2014-10-19
@iusfof

your

$(function(){
    obj.show();
});

equivalent to
$(function(){
  function() {
    $('body').on('mouseover', 'div',
      function() {
        $('.name', $(this)).show();
      }
    );
  }
});

try instead
var obj = {
show: function() {
        $('body div').mouseover(function() {
                $('.name', $(this)).show();
        } );
    }
}

do this way:
var obj = {
  show: $('body').on('mouseover', 'div',
    function() {
      $('.name', $(this)).show();
    }
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question