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

Alignment of text fields in a vertical manner

How can I vertically align text input fields using CSS? <form action='<?= $_SERVER['PHP_SELF']; ?>' method='post'> <p><label for='username' class=''>Username:</label& ...

Upon the initial rendering, Next.js obtains access to the query { amp: undefined }

When using Next.js 9.3, I encountered an issue where I needed to access the query on initial render and pass the result of the query to next/head in order to change the title and description of the page. The component is receiving the query from the useRo ...

What causes the failure of making an ajax call tied to a class upon loading when dealing with multiple elements?

I can see the attachment in the console, but for some reason, the ajax call never gets triggered. This snippet of HTML code is what I'm using to implement the ajax call: <tr> <td>Sitename1</td> <td class="ajax-delsit ...

Is it possible for an HTML checkbox value to store a boolean rather than a string?

Strings are held by HTML Input values. For instance: This stores the string "yes". <input type="checkbox" name="checkThis" value="yes"> Nevertheless, for checkboxes it is sometimes beneficial if the value was a boolea ...

What is the best way to experiment with angular-ui-tinymce within a tabset using Plunker?

I am currently experimenting with angular-ui-tinymce by incorporating it into a Plunkr. Can anyone assist me in integrating the necessary files for angular-ui-tinymce into the Plunkr so that I can showcase its functionality? Currently, I have this Plunker ...

Reversing the direction of an owl carousel slider to slide from right to left

I am looking to reverse the slider for Arabic language to change its behavior. Prevoius [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] Next Imagine that here 1 to 10 are blocks containing headings and descriptions. Therefore, I would like to reverse this ...

Persisting Undefined Values Even After Proper Prop Passing

I'm currently working on fetching and passing coaching data as props to another component for rendering on the frontend. I need to pass these props to the CoachingCard Component in order to display the coaching values. However, I'm encountering ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

Is there a way to apply -webkit-text-fill-color using pure vanilla JavaScript?

My website features two a links, and I am utilizing JavaScript to set their href attributes. When there is no link provided, the color changes to black. However, in Safari on iPhone, achieving the correct color requires the use of -webkit-text-fill-color ...

Issue with incorporating Material UI HtmlTooltip within Material UI Select MenuItem and handling synthetic events in the select onChange method

---OBJECTIVE--- The goal is to integrate a Material UI select component with MenuItems wrapped in HtmlTooltips, providing hover information for each option in the list. For now, I'm keeping it simple as a proof of concept and plan to implement dynam ...

The header and footer are not extending across the entire width of the page

While testing on a responsive screen, I noticed that the header and footer both decrease in width instead of maintaining 100% width as intended. The issue only occurs when I reduce the width of the screen. body{ margin: 0; padding: 0; box-si ...

Convert TypeScript model to JSON while excluding properties with null values

When working with an Angular 4 App and a typescript model, I have defined a Person class as follows: export class Person{ fname:string, lname?:string } The 'lname' property in the model is optional. To populate the model in a component, I u ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

Getting the initial date of the upcoming month in JavaScript

I'm trying to figure out how to get the first day of the next month for a datePicker in dd/mm/yyyy format. Can anyone help? Here's the code I currently have: var now = new Date(); if (now.getMonth() == 11) { var current = new Date(now.getFu ...

In my Express Javascript application, I recently encountered a challenge where I needed to export a const outside of another

I am currently working with a file named signupResponse.js const foundRegisterUser = function(err, foundUser){ if(!err){ console.log("No errors encountered") if(!foundUser){ if(req.body.password == req.body. ...

What could be causing the getTotals() method to malfunction?

I have been working on a finance app that is designed to update the "income", "expenses", and "balance" tables at the top each time a new item is added by the user. However, the current code seems to be failing in updating these values correctly based on u ...

calculation of progress bar advancement

I want to make the progress bar in my game responsive to changes in the winning score. Currently, it moves from 0% to 100%, which is equivalent to 100 points - the default winning score. But I need the progress bar to adjust accordingly based on the user-i ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

"Exploring the Dynamic Duo: Ajax_JQUERY and the Power of

I am a beginner in Laravel and I'm looking to include edit and show buttons in the Controller using my controller below <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class LiveSearch extends Contr ...

Utilizing reusable functionalities within Vuex

Currently, while working on my NUXT project, I am facing a situation where I find myself repeatedly copying the same actions into multiple store modules. To streamline this process, I have extracted these actions into a separate file and now import them in ...