Switch between display modes using a button and CSS media query

I'm trying to find the most effective method for toggling display states on a webpage using a button while also being able to adjust based on screen size. For larger screens, I want to default to a horizontal layout with the option to switch to vertical. On smaller screens, the default should be vertical with no toggle available.

My current approach involves using cascading styles in the stylesheet, but I would prefer to avoid this as it requires careful order of styles.

HTML:

The default layout is set to layout--horiz, with the layout class used to override specific layouts with @media queries.

<div id='layout' class='layout layout--horiz'>
  <a href="#" id='btn'>Toggle</a>
  <p>This</p>
  <p>is</p>
  <p>a</p>
  <p>test</p>
</div>

CSS:

In the @media query for small screens: hide the toggle button and apply the vert styles directly to the layout class to override layout--horiz if necessary.

#btn {
  display: block;
}

.layout--horiz p {
  display: inline;
}
.layout--vert p {
  display: block;
}

@media screen and (max-width: 600px) {
  #btn {
    display: none;
  }

  .layout p {
    display: block;
  }
}

JS:

To toggle between --horiz and --vert classes upon button click.

$('#btn').click(function() {
  $('#layout').toggleClass('layout--vert layout--horiz');
});

This solution is functional, but I am open to suggestions for improvement.

Note: Feel free to experiment with this code on CodePen.

Answer №1

Your solution is almost optimal, but it could benefit from incorporating your JS into a frontend framework. This may be why you're being advised to seek code review feedback. To enhance your solution, consider using only one selector for state changes. This will create two states in your layout: layout--horiz and a default state. Making this adjustment is simple once you modify your media query to target large displays instead of small ones.

Here is the HTML snippet:

<div id='layout' class='layout layout--horiz'>
  <a href="#" id='btn'>Toggle</a>
  <p>This</p>
  <p>is</p>
  <p>a</p>
  <p>test</p>
</div>

And the corresponding CSS code:

#btn {
  display: none;
}

.layout p {
  display: block;
}

@media screen and (min-width: 601px) {
  #btn {
    display: block;
  }

  .layout.layout--horiz p {
    display: inline;
  }
}

Finally, here's the JavaScript part:

$('#btn').click(function() {
  $('#layout').toggleClass('layout--horiz');
});

Answer №2

In my opinion, an effective approach to address this issue could involve utilizing two distinct style sheets – one for horizontal layout and another for vertical layout. By implementing a click function that switches between these style sheets, users can easily toggle between their preferred layouts. For more information on this technique, check out the following resource:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate a function within Bootstrap JavaScript

Is there a way to temporarily disable a function within Bootstrap after a click event? <a href="#"><span class="glyphicon glyphicon-triangle-right" id="btn04" onclick="myfun();"></span></a> Additionally, I am looking for a soluti ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

Loading data from controller in view using Ajax with a 'loading' indicator

Currently, I am fetching data using cURL in my controller and displaying it on my view file. However, the loading time from cURL is quite long, which results in extended loading times for my website. I would like to implement a loading effect that display ...

How can we use Python and Selenium to retrieve the text from HTML that includes the <p> tag?

I have a simple question that I hope you can help me with. I'm not feeling well and struggling to complete my presentation because my brain just isn't functioning properly. Here is the HTML code in question: <p> <b>Postal code:& ...

Step-by-step guide on embedding a function in HTML using vbscript

I'm working on a dynamic HTML list that I want to enable or disable based on user input. Typically, you can just use the "enabled" or "disabled" attribute at the end of the select element to control the entire list. However, I'm unsure how to ach ...

What is the best approach to implementing a blur function for a specific input within a parent component?

I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives: <app-input ...></app-input> My goal is to pass the blur event/function to the parent component speci ...

Learn how to utilize jQuery and Anything Slider to showcase the identification of the current slide in your web presentation

I am attempting to dynamically display the ID of the current slide in another div when the slide changes. Here is a snippet of the code I have been working on: $(function(){ $('#slider').anythingSlider({ onSlideInit: function(e,slider){ ...

What is the best way to organize controls on my website?

My web page controls need to be organized in the specific layout below: Header Left Content - Main Content - Right Content Footer Is there a control available that can assist me with achieving this layout? I prefer not to use a table since it may not b ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Differences in rendering with Google Chrome when zooming in or out

After creating some code, I observed a peculiar issue. At 500% zoom, the DOWNLOAD button aligns perfectly with the left wall without any gap. However, upon reducing the zoom to 250%, a green background segment becomes visible. To witness this anomaly, refe ...

Pressing the reset button will initiate once the loader has finished

Hello everyone, I'm currently working on creating a button that transforms into a loader when submitted and then reverts back to a button after the form is successfully submitted. I suspect the issue lies within my JavaScript. I'm not sure how ...

What Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

The disabled feature doesn't seem to be functioning properly with the <i> tag when using Font Awesome icons

I've designed a plunk where I'm trying to validate a form with a button featuring a font-awesome icon. The text field is mandatory and I'd like to disable the icon if no data has been entered. However, it seems that ng-disabled doesn't ...

What could be causing my jQuery $(this).next().removeAttribute to not function properly?

I am currently working on a file upload form that includes buttons like "Choose file", "Upload", and "Add other file". I am facing an issue where the "disabled" attribute is successfully removed from the first Upload button upon File Input change, but it ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

A guide on updating the value of a two-dimensional array using the useState() hook

Take a look at this Codesandbox example demonstrating my issue. Experiment by typing some words into both text areas to observe the problem. I have just started learning React. My goal is to dynamically generate an svg element based on user input. I am br ...

An issue occurred when attempting to retrieve JSON data using an Ajax

After making an ajax call below, I encountered an error that left me puzzled. The variable 'response' in the success function is structured as follows: {"status": "complete", "username": "test", "error": "0", "message": ""} Surprisingly, when I ...

unable to send array in cookie through express isn't functioning

Currently, I am in the midst of a project that requires me to provide the user with an array. To achieve this, I have been attempting to utilize the res.cookie() function. However, each time I try to pass an array as cookie data, the browser interprets it ...