Using Jquery and CSS to display or conceal table elements depending on viewport width

I am seeking advice for my issue. Here is the code snippet on JSFiddle.

I have a list of models and corresponding values that vary across different categories. I have created a simple table to display this data. However, I need to alter the table structure when the viewport width is less than or equal to 640px to only show one category at a time, making it clickable for value changes.

The problem arises when I resize the screen. If the screen size is 640px or below and I click on a category (thus changing the values) then resize back to a larger screen size, the table should display all values again. Any help with jQuery fixes would be greatly appreciated.

JS:

$('a.cashback-btn').click(function(event) {
  if ($(this).hasClass('active')) {
    $('.cashback-block .cash-table').slideUp('fast');
    $(this).find('i').removeClass("fa-chevron-up");
    $(this).find('i').addClass("fa-chevron-down");
    $(this).removeClass('active');
  } else {
    $('.cashback-block .cash-table').slideDown('fast');
    $(this).find('i').removeClass("fa-chevron-down");
    $(this).find('i').addClass("fa-chevron-up");
    $(this).addClass('active');
    $('html, body').animate({
      scrollTop: $('a.cashback-btn').offset().top
    }, 1000);
  }
});

var medalsCnt = 1; // 1-3, 4-6, 7-10, >10
var medalsMsg = "1-3 category";
$('.cash-table th.mobile').click(function() {
  medalsCnt++;
  $('.cashback-block table td:not(:first-child)').hide();
  if (medalsCnt == 2) {
    medalsMsg = "4-6 category";
    $('.cashback-block table td:nth-child(3)').show();
  } else if (medalsCnt == 3) {
    medalsMsg = "7-10 category";
    $('.cashback-block table td:nth-child(4)').show();
  } else if (medalsCnt == 4) {
    medalsMsg = "more 10 category";
    $('.cashback-block table td:nth-child(5)').show();
  }
  if (medalsCnt > 4) {
    medalsCnt = 1;
    medalsMsg = "1-3 category";
    $('.cashback-block table td:nth-child(2)').show();
  }
  $(this).find('span').text(medalsMsg);
});

UPDATE

$( window ).resize(function () {
     if($('.mobile-version').is(":visible")){
        return; //need to show/hide only one column based on category selected
     }
     else{
        $('.cashback-block table td').show(); //works ok, but now mobile version is not working
     }
  });

Answer №1

let windowWidth = $(window).width();
if(windowWidth <= 640){
    // select the table row you want to be clickable
    // add click event
        // execute code
}

Utilize CSS media queries to modify the appearance of the table. Conceal any unwanted table rows to customize the display.

Answer №2

Implement these modifications in your code and hopefully it will resolve the issue.

$(window).resize(function(ev) {
    console.log(ev);
    if ($('.mobile-version').is(":visible")) {
        return; //only show/hide one column based on selected category
    } else {
    }
          if($(window).width()<=640){
            $('.cashback-block table td:not(:first-child)').hide();
            $('.cashback-block table td:nth-child('+(medalsCnt+1)+')').show(); //functions correctly, but mobile version is now disrupted                
        }else{
            $('.cashback-block table td').show();
        }
});

Check out the JS Fiddle for reference: https://jsfiddle.net/nepovx0e/7/

Answer №3

To prevent multiple event attachments on element resizing below 640px, it is recommended to check the window width and create a variable for binding the event only once. Failure to do so will result in the same event being attached every time the width is resized below 640px.

var eventBound = false;
if ($(window).width() <= 640 && !eventBound) 
{ 
    // Bind your event here.
    eventBound = true;
}   

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

Where should I place my elements to ensure proper positioning in the Code Generator?

Hey everyone, I've been working on developing a code generator similar to Sketch2Code and I've hit a roadblock with my JSON structure. I'm trying to create an HTML page using the myData example provided with a predefined HTML structure. Thin ...

Encountered a failure while loading modules in AngularJS

When I tried opening the index.html page using Chrome, I encountered an error stating that the correct modules could not be found. Uncaught SyntaxError: Unexpected token < angular.js:1 Uncaught SyntaxError: Unexpected token < controller.js:1 ...

How do you manage conditional formatting within HTML forms?

On one of my HTML pages, I am using the following code snippet: {% for bet in recent_bets %} {% if bet.status__name == "Won" or bet.status__name == "Half Won"%} <div class="container col recent-form_col bg-success" data-toggle="tooltip" da ...

Styling Process Steps in CSS

Just starting out with CSS! I'm looking to replicate the Process Step design shown in the image. https://i.stack.imgur.com/Cq0jY.png Here's the code I've experimented with so far: .inline-div{ padding: 1rem; border: 0.04rem gray ...

What is the method to allocate the smallest available number that has not yet been assigned?

As I'm dynamically generating elements and adding them to the page, each element needs a unique numerical id. However, due to non-linear removal of elements, there can be gaps in the assigned ids. For example... In one scenario: 1, 3, 4, 5, 16, 22. ...

What are some ways to stop the default event action from occurring when a parent HTML element has an event handler attached to it?

I have a bunch of hyperlinks on my webpage that I want to ajaxify so that clicking on a link deletes the associated item. I attached an event handler to a parent container like this: <div id="parent"> <a href='#' data-itemid='1& ...

The CSS background fails to expand to the entire height of the element

I'm encountering an issue where an element with 100% height is extending beyond its boundaries when there are multiple blocks. For a demonstration, you can refer to this jsfiddle example: http://jsfiddle.net/yPqKa/ Any suggestions on how to resolve ...

Trouble with CSS animations in ThreeJS's CSS3DRenderer

Seeking a way to incorporate plain text (2D or 3D) into a threeJS scene while applying CSS effects, I stumbled upon this resource. It seemed to offer the solution I was looking for. However, when I tried to apply an animate.css class (a well-known CSS anim ...

Tips for managing pagination in a Single Page Application

Within my Single Page Application (built with Javascript and AngularJs), I have an items list that is paginated, displaying 10 items per page. To ensure that the user's current pagination remains intact even when navigating to other pages, I store th ...

Issues with implementing @font-face on a singular font

I've encountered an issue while setting up a website for a client concerning the fonts. Most fonts are displaying correctly, but there is one font, "chunkfive", that is not working as expected. The problem becomes more severe in Internet Explorer wher ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

Tips on redirecting the treeview menu using Material-UI 4

Currently, I am utilizing Material UI 4's Treeview component. However, I am struggling to figure out how to include a parameter that allows me to redirect to other pages when the user clicks on an item. In the past, I relied on a different method. Ch ...

I am looking to concatenate the existing URL with the language segment using jQuery

Looking to update the URL when clicking on a language name? Simply add the current path after the language section. For example, change the URL https://example.com/de_DE/about-us/ to https://example.com/us_EN/about-us/ and vice versa. I attempted this code ...

Accessing a key from an object dynamically in a React list and resolving key error issues in React

I encountered two challenges: I am currently retrieving JSON data from APIs. [ { "title": "Basic Structures & Algoritums", "lesson_id": 3, "topics": { "Title": &q ...

Leveraging jQuery's AJAX capabilities in combination with VBscript's request

I'm having trouble transferring values between pages using the jQuery ajax() function. It seems like the request.form on my VBscript page isn't capturing the data I'm sending through the ajax() function in jQuery. This is the javascript fu ...

Creating a Custom Rule for Checkbox Validation using jQuery

Can the jQuery Validation plugin be used to validate custom values on checkboxes, rather than just True or False? For instance: <input id="test" type="checkbox" name="test" value="something"> I am struggling to find a method that can check if &apo ...

What steps do I need to follow to execute React/Next code that I have downloaded from GitHub?

I recently obtained a zip file from https://github.com/prgrms-web-devcourse/Team_Price_Offer_FE and extracted its contents. When attempting to launch the program in Visual Studio Code, I inputted the command npm start but encountered an issue. Team_Price_ ...

What is the process for placing the error (404) page in the "dist" folder in a nuxt project?

I successfully implemented an error page following the documentation provided. https://nuxtjs.org/docs/2.x/concepts/views#error-page To achieve this, I created an error.vue file in the /layouts directory and assigned a custom layout to it. <template&g ...

Tips for expanding the boundary of a Font Awesome icon

The image is in a h1 editing margin of h1 only edits margin-left increases the margin on the left of the image. trying to increase margin of i element does nothing either on i element does nothing either. <h1 class="display-4"><i class="fas fa- ...

Issue with Thickbox - showing up towards the end of the page

I'm encountering a strange issue with a PHP page in Wordpress. When I include an inline Thickbox on the page and try to open it, the Thickbox appears at the very bottom of the page, below the footer. Interestingly, I copied the generated HTML code an ...