fgnass / spin.js

A spinning activity indicator
http://spin.js.org
MIT License
9.3k stars 1.02k forks source link

jquery insertBefore works differently than JavaScript #305

Closed scottg521 closed 6 years ago

scottg521 commented 8 years ago

I tried using spin.js in an Angular JS application, where elements are jquery objects. Jquery seems to have an .insertBefore function that inserts the parameter BEFORE (i.e. as a parent of) the target. That meant that when the spinner element was removed, it took out the whole DOM tree where my grid was displayed.

Jquery .prepend does what JavaScript's .insertBefore does, so changing

if (target) {
  target.insertBefore(el, target.firstChild || null)
}

to

if (target) {
  target.prepend(el)
}

solved my problem...but because it is supposed to work with or without jquery, I was surprised that I needed that. Perhaps checking for a jquery element and using a different statement if found would be wise.

fgnass commented 8 years ago

Spin.js expects a raw DOM element as target, not a jQuery or Angular wrapper. Use new Spinner().spin(angularElement[0]) instead of new Spinner().spin(angularElement) and you should be fine. insertBefore btw is the DOM API, not jQuery in this case: https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore

viniciusllima commented 7 years ago

The problem happened to me when I set my target using document.getElementsByClassName and not document.getElementById instead.

I solved my problem using getElementById to set the target.

MattMcMurray commented 6 years ago

@viniciusllima I had the same issue when selecting by class name. The difference is that getElementsByClassName() is returning an array, whereas getElementById() returns a single element. Solve this problem by using document.getElemensByClassName()[0]