Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting flexbox display with jquery for multiple browsers?

having a bit of trouble. I need to have something switch from display: none to display: flex, display: flex-box, and display: -ms-flexbox but it seems to be breaking my code.. Here's what I have so far:

$(elem).css({'display': 'flex', 'display': '-webkit-flex', 'display':'-ms-flexbox'});

and while this works:

$(elem).css({'display': 'flex'})

I need to have the other two for safari and IE10. Is there any way of writing this so that it doesn't break my code? Jquery seems confused by this syntax.

like image 707
shan Avatar asked Jan 12 '23 04:01

shan


2 Answers

I just ran across the same issue. The problem is that you can't specify multiple values of display in the same object, because you can only have one object member called display.

If you're not worried about accidentally removing any other element-level styles, this is one way around:

$(elem).attr('style', 'display: -webkit-flex; display: flex');

(and of course add the extra one for IE10 if you need to).

Sorry to be so late to the party, but maybe it will help others.

like image 153
eaj Avatar answered Jan 18 '23 19:01

eaj


I too ran into this issue and @eaj has excellent insight into why this occurs. I took a slightly different approach since I was using flexbox on other elements. I assigned a class like this:

.flex-container{
    display: -webkit-box !important;
    display: -moz-box !important;
    display: -ms-flexbox !important;
    display: -webkit-flex !important;
    display: flex !important;
}

Then instead of trying to change it via adding inline styles, you can just add the class like so:

$(elem).addClass('flex-container');

The !important in the class will override the existing display:none forcing it into visibility. There are a couple of advantages here: it's a lot cleaner semantically, it's easier to add additional flexbox properties if you need them (my actual .flex-container class had ~20 different properties due to the prefixes for center alignment), easier to reuse the same class for other elements, and finally if you need the element to dissappear again gracefully you can just call removeClass().

like image 31
jwhazel Avatar answered Jan 18 '23 21:01

jwhazel