开发者

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 fi开发者_如何学编程ne. Can someone suggest what can be problem with following code:

jQuery(document).ready(function($){ 
    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 jQuery(document).ready(function($){ 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.


Get rid of that piece of code, and add the following CSS rule:

#showbar {
    position: fixed;
}

This is an universal way to keep an element at the same position, even when the user scrolls. The CSS method requires less computing power than the JavaScript implementation.

If you still want to use JQuery, check this page: http://wpapi.com/wordpress-and-jquery-conflicts-how-to-solve-that/


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.


Your way of creating the scroll event is pretty nonstandard. Instead of:

jQuery.event.add(window, "scroll", showbar);

why don't you try:

jQuery(window).bind('scroll', showbar);

There's a chance that might solve your issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜