Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Of JQuery Remove Causing "Undefined" Error

Tags:

jquery

append

I have added a plugin called scrollpaper to a site I'm working on. The plugin is used on both static pages, and on html snippets I append to the site.

The problem is, when the appended snippets which call the function are removed, using:

$(this).remove();

I get the following error relating to the scrollpaper plugin:

TypeError: 'undefined' is not an object (evaluating 'data.clearer')

The error occurs the moment the snippets are removed. It doesn't cause any actual performance problems, and the plugin is still successfully called and executed when I re-append the snippets, but the errors do stack up, and I'd very much like to fix them.

The main plugin file is included at the foot of every page, with a call made for the static pages added below it:

<script src="js/jquery.scrollbarpaper.js"></script>
<script type="text/javascript">
$(function() {
    $('.scrollpaper-trigger').scrollbarPaper();
});
</script>

A second call is added to the appended html:

<script>
$(function() {
    $('.scrollpaper-trigger-lightbox').scrollbarPaper();
});
</script>

How To Recreate The Problem:

  1. Open web inspector/fire bug
  2. Launch either the full, party, set menu or the reserve online form
  3. Either close the opened element by clicking on the overlay/close button, or switch between the menus at the bottom of the menu page.
  4. This will trigger the error

To fix the problem myself, I've so far tried only adding the base plugin file to the appended elements (and ignoring the static pages), I've also tried using .html('') and .empty(''). In place of .remove(), but that hasn't helped.

I've only been working with JQuery for a couple of months, so whilst I'm becoming familiar with how it all works, and I'm keen to learn best practices. However, this problem is beyond me at present, so any and all help would be hugely appreciated.

Menu Flipping Script:

$('.other-menus a').click(function() {
var url = $(this).attr('data-url'); 

$('.switch').fadeOut(500,
function() {
$(this).detach();
$('<div></div>').load(url).fadeIn(800).appendTo('.switch-wrap');

})

});
like image 381
Dave Avatar asked Feb 11 '26 05:02

Dave


1 Answers

You're removing the element from the DOM using .remove, but this will clear all .data items, including the object stored at the "scrollPaper" key. The scrollpaper plugin is accessing properties on the object retrieved from .data("scrollPaper"), so when it starts returning undefined it throws an exception.

You want .detach instead in scripts.js:

$(this).detach(); //Removes Element From DOM
like image 104
pimvdb Avatar answered Feb 16 '26 16:02

pimvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!