CH4B
CH4B

Reputation: 774

Jquery and @media in CSS

Hello there!

I have an Angular project, where i'm working with HTML, CSS and Jquery. I have a paragraph set with "display: none", and I want it to appear only when the user click a "button" tag. The thing is, the CSS is inside a @media annotation. And I can't put it inside the Paragraph tag like "style=@media all and...." as the HTML file does not compile with the annotation. It has to be inside a specific CSS document. Thanks to that, I cannot use Jquery to override the display of the Paragraph tag.

This is how it goes:

HTML:

<p id="two">
    The history of ...</p>

CSS:

@media all and (max-width: 580px) {

   p#two
   {
       display: none;
   }

}

Jquery:

$(document).ready(function(){
    $("p#one button").click(function(){
      $("p#two").attr("style", "display: normal")
    });
});

I also tried a Jquery like:

    $("p#one button").click(function(){
      $("p#two").css({"display" : "normal"});
    });

or

$("p#one button").click(function(){
      $("p#two").css({
        display : 'normal'});
    });

But nothing seems to override the "display: none". What can I do to fix this problem?

Upvotes: 0

Views: 263

Answers (2)

Mandy
Mandy

Reputation: 21

You can use simple way to resolve this problem:

@media all and (max-width: 580px) {

    p.hidden-class {
       display: none;
    }

    p.visible-class {
        display: block;
    }
}

And toggle your class with ngClass.

Upvotes: 2

arieljuod
arieljuod

Reputation: 15838

Personally, I don't like to mix css properties with javascript unless it's really really really necessary.

You can add a class for p#two that overrides the display: none property and toggle that class on on click.

@media all and (max-width: 580px) {
   p#two { display: none; }
   p#two.show { display: initial; } // "normal" is not a valid value for display
}

Then, on your click event handler, you add the class:

document.getElementById('two').classList.add('show')

Note that normal is not a valid option for display and also that both jquery and angular can handle showing element with their own methods like $('#p').show() of the ng-if directive.

Upvotes: 2

Related Questions