Utilizing media queries to customize the appearance of a jQuery accordion widget

Hello, I'm struggling with implementing a jQuery accordion for mobile platforms that destroys itself on larger screens. While my code is mostly working, I've encountered two issues:

  1. The accordion only gets destroyed when the window is resized, not when the document loads.

  2. Once the accordion is destroyed, I can't get it to work again when resizing back to mobile sizes.

Here's the code snippet in question:

<div class="content-wrap">
            <div class="container">
                <div class="row">
                    <div class="content-fill">
                        <div class="content">
                            <div class="testimonials col-md-6 col-lg-6">
                                <h1>section 1</h1>
                                <p>this is a paragraph</p>
                            </div>
                            <div class="social col-sm-6 col-md-3 col-lg-3">
                                <h1>section 2</h1>
                                <div class="social-wrap">
                                    <a class="twitter-timeline" width="100%" data-chrome="transparent noscrollbar" href="https://twitter.com/xxxxxx" data-widget-id="383311602641952769">Tweets by @xxxxxx</a>
                                </div>
                            </div>
                            <div class="news col-sm-6 col-md-3 col-lg-3">
                                <h1>section 3</h1>
                                <p>this is a paragraph</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

  // <![CDATA[
     var $ = jQuery.noConflict(); $(document).ready(function()
    { 

        $('.content').addClass('accordion');

        $(window).resize(function() {
            if ($('.social').css('float') == 'left')    {
                $('.content').accordion('destroy');
            } else if($('.social').css('float') == 'none')   {
                $('.content').accordion('enable');
            }
        });

         $(".accordion").accordion({
            collapsible: true,
            header: "h1",
            heightStyle: "fill",
            });

            //getter variables
            var collapsible = $(".accordion").accordion("option","collapsible");
            var header = $(".accordion").accordion("option","header");
            var heightStyle = $(".accordion").accordion("option","heightStyle");

            $('.carousel').carousel({ interval: 4000, cycle: true }); 

        }); // ]]>

Answer №1

Swap destroy with disable and include a listener for the load event:

function accordionSwitch() {
    if ($('.social').css('float') == 'left')    {
        $('.content').accordion('disable');
    } else if($('.social').css('float') == 'none')   {
        $('.content').accordion('enable');
    }
}

$(window).on('resize load', accordionSwitch);

According to the Accordion documentation, using the destroy method

completely removes the accordion functionality, bringing the element back to its pre-init state.

Answer №2

Have you considered utilizing media queries to show the accordion on smaller screens and hide it on larger screens?

@media (max-width: 797px) {
    .accordion {
        display: block;
    }
}

Your default styling should be:

.accordion {
    display: none;
}

Answer №3

Avoid enabling and disabling your accordion component. Instead, switch between functions based on the screen size. This approach offers a simpler solution that eliminates the need to constantly trigger a function during screen resizing events.

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

Demonstrating various elements within an application using Vue3

I created two components and attempted to display them in a Vue 3 application. Here is my HTML code: <div id="app"> <image_preview> URL: [[image]] </image_preview> <file_uploader> Counter:[[coun ...

Image transformation not rotating the image

I'm having trouble making an image of an X rotate 180 degrees when it's hovered over. Instead of rotating, the image just moves up and to the right. What am I missing that's preventing this from looking like a smooth 180-degree spin? .bl ...

The combination of Bootstrap and Django does not support responsive design

My code is not working correctly, and I'm struggling to identify the errors. The website I'm working on has subpages, but the responsive design doesn't seem to be functioning properly. Could this issue be related to mistakes in my HTML/CSS c ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: But I want this instead: Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

Prevent individual elements from shifting around on browser resizing within a React form

Having issues with a React form that includes an image gallery and input fields. import React, { Component } from 'react'; import ImageGallery from 'react-image-gallery'; import { Container, Row, Col, InputGroup, Button, FormControl, ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

What is causing the inability to successfully copy and paste Vega editor specs locally?

I successfully executed this spec in Vega Editor: { "$schema": "https://vega.github.io/schema/vega/v3.0.json", "width": 1, "height": 1, "padding": "auto", "data": [ { "name": "source", "values": [ {"name": "Moyenne","vo ...

IE/Firefox returning empty value for Ajax requests

After spending two days trying to solve the issue, I still can't figure out why this code is failing in IE (v11) and Firefox while working fine in Chrome. I have read many questions on similar topics involving caching problems with multiple Ajax call ...

Breaking down the initial state within a redux reducer

Can you explain the distinction between returning state in the default case of a Redux reducer using return state and return { ...state } ? ...

Utilizing an Ajax request for a polling system

I am in need of adding a polling mechanism to call a web service from my webpage. To achieve this, I am attempting to utilize an ajax call within a javascript page. However, I am fairly new to both ajax and javascript. Below is the code snippet that I have ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

"Returning undefined: The outcome of using jQuery's .html() method on

I am having an issue with the JavaScript function I have created to load content from another URL into the current document. For some reason, both contentHtml and menuHtml variables are showing as undefined. Can someone please help me identify where I we ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Determine if an Android application has been installed using JavaScript or jQuery

I'm working on an Android app that is also accessible via a web browser. I want to add a banner prompting users to install the Android application if they haven't already. How can I use JavaScript or jQuery to detect if the user has the app insta ...

What is the correct way to utilize browser actions for sending keys with the "?" symbol in Protractor?

I'm facing an issue in my tests with a particular line of code browser.actions().sendKeys(Key.chord(Key.CONTROL, '?')).perform(); Interestingly, it works fine with another symbol. For example: browser.actions().sendKeys(Key.chord(Key.CONT ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

The opacity behavior of jQuery seems to behave strangely on IE10

Within my project, the left side of the content is contained within a div called ".container", and there's a preloader located in an element with the ID "#preloader." Across all major browsers, the functionality works smoothly as intended - when all ...