Damon
Damon

Reputation: 10809

jQuery show function applies inline-block sometimes and block others?

I have a script right now where a certain element is shown and hidden often (similar to a tip). I have noticed that sometimes the inline style says 'display: inline-block' and sometimes it says 'display: block'. The documentation as far as I can see only notes that it will use 'block'.

What appears to be happening, is it's using display: inline-block when the positioning is relative/static and is using display: block when the element is position: fixed but it sets this when the page is loaded and keeps it.

Therefore I have different behaviour if the page is loaded normally compared to if it's loaded while scrolled partway down, because a function applies a style with position: fixed when it's not in view (so that it will always be visible)

$(function() {  
    checkUrlEdit();

    $(window).scroll(function () { 
       checkUrlEdit();
    });

    $('a').hover( 
      function(){
        if(!editObj && !imageUpload){
            $('#urlEdit').show();
            $('#urlEdit').val($(this).attr('href'));}
    },
      function(){
        if(!editObj && !imageUpload){
        $('#urlEdit').hide();}
    } 
);

});

function checkUrlEdit(){
       if (!isScrolledIntoView('#urlEditor')) {
           $('#urlEdit').addClass('floating');

       } else {
           $('#urlEdit').removeClass('floating');
       }
}

function isScrolledIntoView(node)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var nodeTop = $(node).offset().top;
    var nodeBottom = nodeTop + $(node).height();

    return ((nodeBottom >= docViewTop) && (nodeTop <= docViewBottom)
      && (nodeBottom <= docViewBottom) &&  (nodeTop >= docViewTop) );
}

CSS:

#urlEdit.floating {
    position: fixed;
    top: 10px;
    z-index: 99;
}

Upvotes: 1

Views: 1268

Answers (2)

Skylar Anderson
Skylar Anderson

Reputation: 5703

If you don't like the way this is functioning, you can always write your own show/hide plugins with your own custom logic applied. Put this code in your JavaScript:

$.fn.extend({
  myShow: function() {
    return this.css('display','block');
  }, 
  myHide: function() {
    return this.css('display', 'none');
  }
});

Upvotes: 3

roselan
roselan

Reputation: 3775

straight from from the jquery documentation:

With no parameters, the .show() method is the simplest way to display an element:

$('.target').show();

The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

the best way in this situation is, imo, to create a class, a corresponding css rule, and use addClass/removeClass instead of show/hide.

Upvotes: 1

Related Questions