mari mari - 2 years ago 184
Javascript Question

jQuery code breaking other code

I'm using this function to keep a div on the screen when the page is scrolled down. This work fine, however it seem to break some other jQuery code (in the wordpress). The problem is with the following function. If i remove it, other code works fine. Can someone suggest what can be problem with following code:

jQuery.event.add(window, "scroll", showbar);
var sharebar = jQuery('#showbar');
var start = jQuery(sharebar).offset().top;
function showbar() {
var p = jQuery(window).scrollTop();
jQuery(sharebar).css('position',((p+10)>start) ? 'fixed' : 'absolute');
jQuery(sharebar).css('top',((p+10)>start) ? '10px' : '');

Edit: What I meant by 'breaking the code' was that, if i include a javascript having this code in my wordpress theme. The javascript of the wordpress will not work in the control panel of the theme (eg. no lightbox popup by clicking the image upload button etc). The wordpress controls will start working as soon as i remove this code. So obviously theres something wrong with this code.

Edit 2:

I dont seem to get any js errors but i noticed if i wrap the code in
(function() { .. })();
instead of
then the wordpress does not have any problem, but then my code does not work. Can you suggest how can i use function() instead of jQuery(document).ready.. Sorry but i dont have much knowledge of jquery.

Answer Source

In response to your second edit, try putting the (function() { ... })() closure at the very bottom of your file, just above the closing </body> tag. That way, all the relevant DOM elements will already exist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download