View Switch: Last Buttom View Choice (Grid or Line) not Change When Refresh/change page

andysaktia

andysaktia

Posted on September 29, 2021

View Switch: Last Buttom View Choice (Grid or Line) not Change When Refresh/change page

When creating two views i.e. grid and view I also include a button to switch from one to the other. The problem is when you go to a new page/refresh the page, the display is returned to the initial mode, not the view that has been selected. The following script wants to solve this problem.

Alt Text

Purpose

Creates view parameters that are saved and checked every time a new page is opened, and immediately activates the view button according to the saved view parameters

Prerequire

  • Bootstrap classes; d-none
  • Jquery; selection, on click
  • Javascripts; localStore, function

Script

function createItem(typeView) {
  localStorage.myview = typeView;
}


function switchView(options){
    $('#view-option .button-view').addClass('off-view');
    if (options == 'grid'){
      $('#book-view-list').addClass('d-none');
      $('#book-view-grid').removeClass('d-none');
      $('#view-option .button-view[view="grid"]').removeClass('off-view');

    } else {
      $('#book-view-grid').addClass('d-none');
      $('#book-view-list').removeClass('d-none');
      $('#view-option .button-view[view="list"]').removeClass('off-view');
    }
}


$('#view-option .button-view').on('click', function() {
  var option = $(this).attr('view');
  createItem(option);
  switchView(option);

});

// Crosscheck parameter page begin here!
let myView = localStorage.getItem("myview");

if (myView != null){
  switchView(myView);
}

Enter fullscreen mode Exit fullscreen mode

The principle of this script

The script function consists of two, namely the createItem function to store view parameters, besides that there is a switchView function which is a parameter to change the view with if logic script, which acts to change the css view to show/hide the grid/list view.

The active script requires an active click trigger, which executes the createItem and switchView functions; it should be noted that the button view html section has been given a parameter view=grid or view=list, so by taking one of these parameters to be stored and passed to the view switch.

The last script to check the parameters that have been saved and run the switch based on the parameters.

💖 💪 🙅 🚩
andysaktia
andysaktia

Posted on September 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related