Issue with JQuery event handlers becoming unresponsive upon resizing the window

JSBin link: http://jsbin.com/4QLDC/6

Here is the JS code snippet that I have written:

var toggleContent = function (event) {
    $(event.target).siblings().toggle();
};
var showOrHidePanels = function () {
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if (windowWidth < 980) {
        $(".headBar1").siblings().hide();
        $(".headBar1").parent().css("min-height", 0);
        $(".headBar1").css("cursor", "pointer");
        $(".headBar1").on("click", toggleContent);
    }
    else {
        $(".headBar1").siblings().show();
        $(".headBar1").parent().removeAttr("style");
        $(".headBar1").css("cursor", "auto");
        $(".headBar1").off("click", toggleContent);
    }
};
$(function () {
    showOrHidePanels();
});
$(window).resize(function () {
    showOrHidePanels();
});

This is my desired outcome:

If the window width is less than 300px, I want:

  1. The content box to collapse
  2. The headings to turn into clickable links
  3. When a heading is clicked, its corresponding content box should toggle visibility

While the first two are functioning as expected, I am encountering difficulties with the third requirement. The behavior seems to be inconsistent - sometimes it works flawlessly but fails at other times (for example, resizing the "Result" frame multiple times in the JSFiddle page). What could be causing this unpredictability? How can I resolve this issue?

Answer ā„–1

A different method that is more suitable for the current era of impressive browsers is to utilize @media (max-width: 300px). This can be used by all modern browsers and allows for the application of specific CSS rules.

/* Specify CSS rules for when the window width is greater than 300px */

@media (max-width: 300px) {
    /* Adjust parent's minimum height and other settings */
    /* Hide or display relevant content with display: none and display: block */

    .headBar {
        cursor: pointer;
    }
}

Personally, I find this method effective in making the website mobile-friendly and compatible with smaller windows. Once you understand how it works, it performs perfectly.

Most modifications involve working with CSS anyway. As long as you have a well-organized structure of classes, you should be all set.

Answer ā„–2

function toggleContent(event) {
    $(event.target).siblings().toggle();
};
function showOrHidePanels() {
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    $(".headBar1").off("click");
    if (windowWidth < 300) {
        $(".headBar1").siblings().hide();
        $(".headBar1").parent().css("min-height", 0);
        $(".headBar1").css("cursor", "pointer");        
        $(".headBar1").on("click", toggleContent);
    }
    else {        
        $(".headBar1").siblings().show();
        $(".headBar1").parent().removeAttr("style");
        $(".headBar1").css("cursor", "auto");       
    }
};
$(function () {
    showOrHidePanels();
});
$(window).resize(function () {
    showOrHidePanels();
});

Does this meet your requirements?

Answer ā„–3

Here is the solution you requested: http://jsfiddle.net/4QLDC/8/

function toggleContent(ths) {
    console.log('toggle!');
    $(ths).siblings().toggle();
};
var showOrHidePanels = function () {
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if (windowWidth < 300) {
        console.log('Under: ' + windowWidth)
        $(".headBar1").siblings().hide();
        $(".headBar1").parent().css("min-height", 0);
        $(".headBar1").css("cursor", "pointer");
        $(".headBar1").on("click.toggle", function(){ toggleContent(this); });
    } else {
        console.log('Over: ' + windowWidth)
        $(".headBar1").siblings().show();
        $(".headBar1").parent().removeAttr("style");
        $(".headBar1").css("cursor", "auto");
        $(".headBar1").off("click.toggle");
    }
};
$(function () {
    showOrHidePanels();
});
$(window).resize(function () {
    showOrHidePanels();
});


I have improved the code structure by moving styles to CSS and using one class for easy manipulation. You can see the updated version here: http://jsfiddle.net/4QLDC/12/

CSS:

.botContentBox {
    min-height: 200px;
    float:left;
    clear:none;
    border: 1px solid grey;
    margin: 0 10px 10px 0
}
.headBar1 {
    cursor: default;
    background-color: #880000;
    border:5px solid #fff;
    color:#fff;
    font-size:17px;
    line-height:17px;
    padding:10px 10px;
    width:auto;
    margin:0 0 5px 0
}
.botContentBox.lt300{
    min-height: 0px;
}
.botContentBox.lt300 .headBar1{
    cursor: pointer;
}
.botContentBox.lt300 .botContentHolder{
    display: none
}

JS:

var showOrHidePanels = function () {
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if (windowWidth < 300) {
        console.log('Under: ' + windowWidth)
        $(".headBar1").parent().addClass('lt300');
        $(".headBar1").on("click.toggle", function(){ $(this).siblings().toggle(); });
    } else {
        console.log('Over: ' + windowWidth)
        $(".headBar1").siblings().show(); // in case it was toggled on/off
        $(".headBar1").parent().removeClass('lt300');
        $(".headBar1").off("click.toggle");
    }
};
$(function () {
    showOrHidePanels();
});
$(window).resize(function () {
    showOrHidePanels();
});

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

Learn how to extract data from the "this" object in JavaScript

Can anyone help me with retrieving the numbers generated by this code snippet? $("#100wattaren") .countdown("2018/01/01", function(event) { $(this).text( event.strftime('%D days %H hours %M minutes %S seconds') ); }); When I con ...

Creating an HTML return statement to specifically target and extract a certain string while disregarding additional data

Looking for a solution to trim a long string returned by a webpage, while ensuring essential data is not removed. Counting characters is not feasible due to the varying length of the return. The return format is as follows: GET /New%20Messenger&subti ...

How can EJS variables be utilized within HTML input fields?

I am facing an issue while trying to use a checkbox to redirect selected users to a new page. I am looking for a solution on how this can be achieved, especially when using mongodb to store the information. Below is my current code snippet: Firstly, I ren ...

Experiencing pagination problems with Vue / Laravel framework

Trying to implement pagination for fetched data in a Vue project, but encountering an issue: New Question Error encountered during rendering: "TypeError: this.estates.filter is not a function" Am I overlooking something here? Pagination.vue ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

Guide on invoking an Angular 1.5 component with a button press

Having just started learning Typescript, I'm struggling to figure out how to call my Angular component "summaryReport" on a button click. Here's a snippet of my code: Let's say I have a button that should call my component when clicked with ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

Knockoutjs is not binding with newly added HTML elements by Ajax after calling ko.applyBindings

Recently, I encountered an issue with an ASP.NET MVC 4 View utilizing KnockoutJs (version 2.3.0). While the page loads smoothly and existing elements with the data-bind attribute function as expected, adding HTML via Ajax containing a data-bind for an obse ...

unable to retrieve parent ID

I am having trouble retrieving the ID of the parent's parent of the event target. It keeps coming back as undefined, but I have verified through firebug that the ID does exist. Below is my HTML markup: <div class="grid-stack-item ui-draggable ui- ...

Is Ursina the right choice for web development?

Looking for a method to compile Ursina for HTML5 using WebAssembly or another technology? I am seeking to make my Ursina Game compatible with Linux & Mac (and potentially Android/iOS with webview), but the current cross-platform compilation options for Py ...

Vue.js - Maintaining input value when model declines updates

I am working on a text input that allows users to enter numbers with a maximum of three digits after the decimal point: <v-text-field type="text" :value="num" @change="changeNum($event)" /> <p>{{ num }}</p> ... export default { data: ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...

Guide to logging in using REST/API with a Next.js application

Issue: I am facing a challenge integrating with an existing repository that was created using Next.js. The task at hand is to enable users to sign in to the application through a specific endpoint or URL. To achieve this, I have been attempting to utilize ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Monitor fetch() API calls and responses in JavaScript

Iā€™m looking to intercept fetch API requests and responses using JavaScript. Specifically, I want to be able to capture the request URL before it is sent and also intercept the response once it has been received. The code below demonstrates how to inter ...