How to hold back JWT token in localstorage even after a page referesh

Iam working in a login logout feature and iam using context api to run the function’s like store token in localstorage and remove it wile logingout . “The problem is after login if i try to refresh the page the token stored in the localstorage is getting remove please tell me how do i encounter with this problem”

code of context :

 import React, {useState, createContext, useEffect} from 'react'
     import { useNavigate } from 'react-router-dom';

     const Authcontext = createContext(); 


     const Usercontext = ({children}) => {

     const navigate = useNavigate() 
     const [user, setuser] = useState(null)
     const [loggedin, setloggedin] = useState(false)
     const [token, settoken] = useState(null)

     useEffect(() => {
      const storedToken = localStorage.getItem('token');
      if (storedToken) {
        settoken(storedToken);
       }
     }, []);

    

    ////// Login activity
    const login = (value) =>{
      // const token = localStorage.getItem('token')
        localStorage.setItem('token', JSON.stringify(value))
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const payload = JSON.parse(atob(base64));
        const currentuser = payload.user;
        setuser(currentuser)
        setloggedin(true)
     }


    ///// logout Activity
    const logout = () =>{
        localStorage.removeItem('token')
        setuser(null)
        setloggedin(false)
        navigate('/')
    }

    console.log(user);

    return (
    <Authcontext.Provider value={{user, loggedin, login, logout}} >
        {children}
    </Authcontext.Provider>
    )
    }

    export  {Usercontext, Authcontext};

here’s my navabar code i’ve been trying to view the name of user in it . here is where the problem refelects after referesh the user name will be changed back to login and register :

import React, { useEffect, useState, useContext } from 'react';
    import { Link } from 'react-router-dom';
    import { Authcontext } from '../context/Usercontext';
    import "../components/css/nav.css"

    export const Navbar = () => {

      const {loggedin, logout, user} = useContext(Authcontext)        

      console.log(user);

      return (
        <div className='navbar' >
          <div >Navbar</div>
           {loggedin ? (
            <div className='userin' >
             {user && user.username}
             <button className='btn' onClick={logout}>Logout</button>
            </div>
            ) : (
            <div className='userout' >
             <Link to="/register" className='register' >Register</Link>
             <Link to="/login" className='login' >Login</Link>
            </div>
           )}
        </div>
      );
    };   

i’ve been trying to login activity with using localstorage . i need the token stored in the localstorage to hold back even after a page referesh

Is it a bug? Javascript changes numeric value of the variable upon assignment

Ok, this will sound crazy, but I’ve tested it on several browsers and three different machines (all Windows though). As soon as I assign specific numeric value to the variable, it immediately increments. The problem for me is that this specific value is one of the database object ids that shouldn’t be changed.

Tried on latest Chrome, Firefox, and Edge. It’s really simple to test:

let a = 17841410687956931;
console.log(a);
// output is 17841410687956932

I’ve also tried let a = [17841410687956931]; and let a = {17841410687956931: "anything"};, and it still increments. const and var don’t change a thing. Note that 17841410687956930 and 17841410687956932 are perfectly fine and do not misbehave.

Am I seeing things? Can this be some easter egg? Can you recommend me a good doctor?

On Select Radio Button of Add then Add +1 in value of same row other column while Table got with the help of Php database

I create a table with the data retrieve from server , Now I need to on select radio button add +1 in the same row one column value but when we selected another one then remove one from last increased value and add +1 in new selected row Colum. As mentionedenter image description here in images on add hotel add +1 in room booked Colum same row room booked.


<pre><code>
<div class="col-lg-12">
  <div class="col-lg-12 text-center">
    <h3>
      <u>Hotel Details</u>
    </h3>
  </div>
  <table class="col-lg-12 hotel-table">
    <thead>
      <tr>
        <th>S.No.</th>
        <th>Room Code</th>
        <th>Roome Type</th>
        <th>Room Tarrif</th>
        <th>GST</th>
        <th>Room Booked</th>
        <th>Room Available</th>
        <th>Add Your Hotel</th>
      </tr>
      <tr>
        <td>1</td>
        <td>RITZ-CD-2</td>
        <td>The Ritz-Carlton Dubai- Executive Double. </td>
        <td>500</td>
        <td>
          <span>18%</span>
        </td>
        <td>
          <input type="text" class="room-add" id="add_hotel-1-1" name="room_booked" value="5 ">
        </td>
        <td class="add_hotel-1">
          <input type="text" value="95">
        </td>
        <td>
          <input type="radio" class="room-add" id="add_hotel-1" name="guest_hotel_name" value="The Ritz-Carlton Dubai- Executive Double.    ">
          <label for="add_hotel-1"> Add Hotel </label>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>RITZ-CS-1</td>
        <td>The Ritz-Carlton Dubai- Deluxe (ROH) Single </td>
        <td>500</td>
        <td>
          <span>18%</span>
        </td>
        <td>
          <input type="text" class="room-add" id="add_hotel-1-2" name="room_booked" value="0 ">
        </td>
        <td class="add_hotel-2">
          <input type="text" value="100">
        </td>
        <td>
          <input type="radio" class="room-add" id="add_hotel-2" name="guest_hotel_name" value="The Ritz-Carlton Dubai- Deluxe (ROH) Single  ">
          <label for="add_hotel-2"> Add Hotel </label>
        </td>
      </tr>
    </thead>
  </table>
</div></code></pre>

Popup blocker in Safari and Google Chrome

How does the popup blocker work in Safari and Google Chrome, or generally in any website?

I realize that asynchronous page redirection will trigger a popup blocker but are there any other factors?

I have made amends to my site where, the user submits their details and I show a modal saying “Thanks for using the site, you will be redirected to xyz page” for 5000ms (5seconds) and then initiate window.open(url, '_blank'). This triggered a popup blocker in Google Chrome and Safari.

So, now I have removed the timeout and and the new page is opening properly in Google Chrome but is still triggering popup blocker in Safari-mobile.

Kindly guide.

Thank you

how to filter out entries of set

for the following contents of data object:

0
: 
{pppId: '005618-00', eppo: 'FAUSY', crop: 'Rotbuche'}
1
: 
{pppId: '005618-00', eppo: 'PSTME', crop: 'Douglasie'}
2
: 
{pppId: '005618-00', eppo: 'QUESS', crop: 'Eiche'}
3
: 
{pppId: '005618-00', eppo: 'YLAGL', crop: 'Langholzpolter'}
4
: 
{pppId: '005618-00', eppo: 'PIEPU', crop: 'Blaufichte'}
5
: 
{pppId: '005618-00', eppo: 'ALUSS', crop: 'Erle'}
6
: 
{pppId: '005618-00', eppo: 'POPSS', crop: 'Pappel'}
7
: 
{pppId: '005618-00', eppo: 'YLAGE', crop: 'Einzelstämme'}
8
: 
{pppId: '005618-00', eppo: 'NNNZG', crop: 'Ziergehölze'}
9
: 
{pppId: '005618-00', eppo: 'ACRCA', crop: 'Acer campestre'}
10
: 
{pppId: '005618-00', eppo: 'YLAGS', crop: 'Schichtholzpolter'}
11
: 
{pppId: '005618-00', eppo: 'PIUSS', crop: 'Kiefer'}
12
: 
{pppId: '005618-00', eppo: 'ABINO', crop: 'Nordmann-Tanne'}
13
: 
{pppId: '005618-00', eppo: 'CIPBE', crop: 'Carpinus betulus'}
14
: 
{pppId: '005618-00', eppo: 'LAXSS', crop: 'Lärche'}

i want to filter out the contents of the object data by the crop name Eiche and Kiefer
i want to make data contains only the 2nd and the 11th entries. in other words, i want data to contain:

{pppId: '005618-00', eppo: 'QUESS', crop: 'Eiche'}
{pppId: '005618-00', eppo: 'PIUSS', crop: 'Kiefer'}

how can i achieve that please

How to set increase or decrease function in cart

when i select the item in cart, it is selected. But when i try to increase the quantity, the price does not change and i have to recheck to update the price. Please help as i cannot figure out how to increase the price when i increase or decrease the quantity of item. I also cannot put increase/decrease function in selectBtn as it would become a loop of number

let quantities = document.querySelectorAll(".quantity-number");
let plusAll = document.querySelectorAll(".plus");
let minusAll = document.querySelectorAll(".minus");

quantities.forEach((quantity, index) => {
  let plus = plusAll[index];
  let minus = minusAll[index];
  plus.addEventListener("click", () => {
    quantity.innerHTML++;
    if (quantity.innerHTML > 1) {
      minus.disabled = false;
    }
  })
  minus.addEventListener("click", () => {
    if (quantity.innerHTML <= 1) {
      minus.disabled = true;
    } else {
      minus.disabled = false;
      quantity.innerHTML--;
    }
  })
});

let items = document.querySelectorAll(".item");
document.querySelector("title").innerHTML =
  items.length + " items found in Cart";

let prices = document.querySelectorAll(".price");
let selectBtn = document.querySelectorAll(".select");
let selectAll = document.querySelector(".selectAll");
let totalItem = document.querySelectorAll(".totalItem");
let totalPrice = document.querySelector(".totalPrice");
let finalPrice = document.querySelector(".finalPrice");

selectBtn.forEach((btn, index) => {
  let price = Number(prices[index].innerHTML);

  selectAll.addEventListener("input", () => {
    if (selectAll.checked == true) {
      if (btn.checked == false) {
        btn.checked = true;
        let quantity = Number(quantities[index].innerHTML);
        if (quantity == 1) {
          price = price;
        } else {
          price = Number(prices[index].innerHTML);
          price = price * quantity;
        };
        totalItem.forEach((total) => {
          total.innerHTML++;
        })
        if (totalPrice.innerHTML == 0) {
          totalPrice.innerHTML = (price).toFixed(2);
          finalPrice.innerHTML = (4 + Number(totalPrice.innerHTML)).toFixed(2);
        } else {
          totalPrice.innerHTML = (Number(totalPrice.innerHTML) + price).toFixed(2);
          finalPrice.innerHTML = (4 + Number(totalPrice.innerHTML)).toFixed(2);
        }
      }
    } else {
      btn.checked = false;
      totalItem.forEach((total) => {
        total.innerHTML--;
      })
      totalPrice.innerHTML = (Number(totalPrice.innerHTML) - price).toFixed(2);
      if (totalPrice.innerHTML == 0) {
        finalPrice.innerHTML = 0;
      } else {
        finalPrice.innerHTML = (Number(totalPrice.innerHTML) + 4).toFixed(2);
      }
    }
  })

  btn.addEventListener("input", () => {
    if (btn.checked) {
      let quantity = Number(quantities[index].innerHTML);
      if (quantity == 1) {
        price = price;
      } else {
        price = Number(prices[index].innerHTML);
        price = price * quantity;
      };

      totalItem.forEach((total) => {
        total.innerHTML++;
      })
      if (totalPrice.innerHTML == 0) {
        totalPrice.innerHTML = (price).toFixed(2);
        finalPrice.innerHTML = (4 + Number(totalPrice.innerHTML)).toFixed(2);
      } else {
        totalPrice.innerHTML = (Number(totalPrice.innerHTML) + price).toFixed(2);
        finalPrice.innerHTML = (4 + Number(totalPrice.innerHTML)).toFixed(2);
      }
    } else {
      totalItem.forEach((total) => {
        total.innerHTML--;
      })
      selectAll.checked = false;
      totalPrice.innerHTML = (Number(totalPrice.innerHTML) - price).toFixed(2);
      if (totalPrice.innerHTML == 0) {
        finalPrice.innerHTML = 0;
      } else {
        finalPrice.innerHTML = (Number(totalPrice.innerHTML) + 4).toFixed(2);
      }
    }
  })
})
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">

<head>
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-[#f5f4f4] hide-scrollbar">

  <div class="">
    <h2 class="text-3xl text-center py-8">Your Cart</h2>
    <div class="md:grid md:grid-cols-3">
      <div class="grid space-y-4 col-span-2">
        <div class="flex justify-between bg-white mx-4 px-4 py-2 border-black border ">
          <div class="flex space-x-4 items-center">
            <input type="checkbox" class="selectAll">
            <p>SELECT ALL</p>
          </div>
          <button>
                        <img class="w-8 h-8" src="../images/main/delete.png" alt="">
                    </button>
        </div>
        <div class="item flex items-center px-4 py-2 bg-white mx-4 space-x-2 border-black border">
          <input class="select rounded-full" type="checkbox" name="" id="">
          <img class="w-20 h-20" src="../images/Cowin-Blue-Wholesale-Aviation-Active-Noise-Cancelling-Headphones-Wired-Gaming-Earphones-Headsets-Bluetooth-Headphones-Wireless/prod1.webp" alt="">
          <div class="grid grod-rows-2 w-full">
            <p class="text-justify text-sm line-clamp-2">Cowin Blue Wholesale: Aviation Active Noise Cancelling Headphones, Wired Gaming Earphones, Headsets, Bluetooth Headphones, Wireless</p>
            <div class="flex justify-between">
              <div class="grid grid-rows-2">
                <p class="text-base font-bold">$<span class="text-xl price">59.99</span></p>
                <p class="text-xs">$<del class="text-sm">79.99</del></p>
              </div>
              <div class="quantity flex items-center space-x-2 py-2 text-white">
                <button class="minus bg-slate-600 w-8 h-8 hover:bg-slate-700 active:bg-slate-800 text-xl flex justify-center">&minus;</button>
                <p class="quantity-number text-black">1</p>
                <button class="plus bg-slate-600 w-8 h-8 hover:bg-slate-700 active:bg-slate-800 text-xl flex justify-center">&plus;</button>
              </div>
            </div>
          </div>
        </div>
        <div class="item flex items-center px-4 py-2 bg-white mx-4 space-x-2 border-black border">
          <input class="select rounded-full" type="checkbox" name="" id="">
          <img class="w-20 h-20" src="../images/Modern-soft-and-comfortable-office-E-sports-club-chair-designed-for-ergonomic-gaming-on-computers/prod1.webp" alt="">
          <div class="grid grod-rows-2 w-full">
            <p class="text-justify text-sm line-clamp-2">Modern, soft, and comfortable office E-sports club chair designed for ergonomic gaming on computers</p>
            <div class="flex justify-between">
              <div class="grid grid-rows-2">
                <p class="text-base font-bold">$<span class="text-xl price">99.99</span></p>
                <p class="text-xs">$<del class="text-sm">119.99</del></p>
              </div>
              <div class="quantity flex items-center space-x-2 py-2 text-white">
                <button class="minus bg-slate-600 w-8 h-8 hover:bg-slate-700 active:bg-slate-800 text-xl flex justify-center">&minus;</button>
                <p class="quantity-number text-black">1</p>
                <button class="plus bg-slate-600 w-8 h-8 hover:bg-slate-700 active:bg-slate-800 text-xl flex justify-center">&plus;</button>
              </div>
            </div>
          </div>
        </div>
        <div class="item flex items-center px-4 py-2 bg-white mx-4 space-x-2 border-black border">
          <input class="select rounded-full" type="checkbox" name="" id="">
          <img class="w-20 h-20" src="../images/New-and-stylish-Auricularess-Bluetooth-earbuds-custom-waterproof-design-perfect-for-immersive-gaming-experiences/prod1.webp" alt="">
          <div class="grid grod-rows-2 w-full">
            <p class="text-justify text-sm line-clamp-2">New and stylish Auricularess Bluetooth earbuds, custom waterproof design, perfect for immersive gaming experiences.</p>
            <div class="flex justify-between">
              <div class="grid grid-rows-2">
                <p class="text-base font-bold">$<span class="text-xl price">24.99</span></p>
                <p class="text-xs">$<del class="text-sm">29.99</del></p>
              </div>
              <div class="quantity flex items-center space-x-2 py-2 text-white">
                <button class="minus bg-slate-600 w-8 h-8 hover:bg-slate-700 active:bg-slate-800 text-xl flex justify-center">&minus;</button>
                <p class="quantity-number text-black">1</p>
                <button class="plus bg-slate-600 w-8 h-8 hover:bg-slate-700 active:bg-slate-800 text-xl flex justify-center">&plus;</button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="checkout bg-white p-4 m-4 md:m-0 md:mr-4 h-fit">
        <p class="font-semibold">Order Summary</p>
        <ul class="py-2 space-y-4">
          <li class="flex justify-between">
            <p>Subtotal (<span class="totalItem">0</span> items)</p>
            <p>$<span class="totalPrice">0</span></p>
          </li>
          <li class="shipping flex justify-between">
            <p>Shipping Fee</p>
            <p>$4</p>
          </li>
          <li class="flex justify-between">
            <p>Total</p>
            <p class="text-blue-600">$<span class="finalPrice">0</span></p>
          </li>
        </ul>
        <button class="bg-orange-500 text-white py-2 w-full mt-5 hover:bg-orange-600 active:bg-orange-500">Proceed To Checkout (<span class="totalItem">0</span>)</button>
      </div>
    </div>
  </div>
  <script src="side.js"></script>
  </div>

ExtJs – grid.column.Column – how to use this as a drop down button

I need to extract these column lists from Ext.grid.column.Column together with the checkboxes and the entire mechanism for the button above the table. I would not like to create the entire mechanism from scratch, but just use the available option. Is it possible?

I would like to have a list of all column names with checkboxes in the Columns button.

Ext.define('ExtModules.ToolbarItems.ColumsList', {

  columnsListButton() {
    return Ext.create('Ext.button.Button', {
      text: 'Columns',
      scope: this,
      handler: () => {
        console.log(this)
      }
    })
  },
})

Object keylist (console.log(this)). the entire object contains too many elements to include it

"viewConfig",
"app",
"control",
"tab",
"webSocketHUBCollection",
"arguments",
"controlConfig",
"moduleVersionConfig",
"controlSettings",
"settingsValueMap",
"titleTpl",
"title",
"id",
"stateful",
"x",
"y",
"width",
"height",
"icon",
"closable",
"tools",
"listeners",
"layout",
"draggable",
"idProperty",
"selType",
"disableSelection",
"multiSelect",
"messageHederTemp",
"dataProvider",
"onRowUpdate",
"customFilter",
"filtersFeature",
"features",
"plugins",
"store",
"columns",
"ownerGrid",
"actionables",
"initialConfig",
"$iid",
"protoEl",
"initConfig",
"isFirstInstance",
"getTwoWayBindable",
"config",
"$observableInitialized",
"hasListeners",
"eventedBeforeEventNames",
"events",
"_addedDeclaredListeners",
"headerBorders",
"activeCounter",
"alwaysOnTop",
"componentLayout",
"componentCls",
"renderData",
"enableLocking",
"pluginsInitialized",
"columnManager",
"visibleColumnManager",
"headerCt",
"scrollTask",
"cls",
"bufferedRenderer",
"managedListeners",
"scrollable",
"view",
"filters",
"items",
"hasView",
"storeRelayers",
"selModel",
"dockedItems",
"reference",
"collapseDirection",
"hiddenOnCollapse",
"stateEventsByName",
"stateEvents",
"inheritedStateInner",
"storeState",
"loader",
"ownerCt",
"inheritedState",
"ownerLayout",
"isLayoutMoving",
"container",
"_renderState",
"ariaRenderAttributes",
"preventChildDisable",
"ariaUsesMainElement",
"initBindable",
"publishes",
"frame",
"scrollFlags",
"uiCls",
"ui",
"activeUI",
"header",
"afterHeaderInit",
"rendering",
"initialCls",
"el",
"body",
"bodyWrap",
"focusEl",
"ariaEl",
"rendered",
"lastBox",
"_keyMapReady",
"keyMapEnabled",
"_keyMapListener",
"syncRowHeightOnNextLayout",
"componentLayoutCounter",
"resizer",
"dd",
"stateTask",
"layoutCounter",
"dataMap",
"tesseract",
"tesseractSession",
"columnDefinitions",
"layoutSuspendCount",
"suspendLayout",
"headerCounter",
"liveRowContexts",
"freeRowContexts",
"bypassSyncColumns",
"focusEnterEvent",
"containsFocus"

localStorage is not available: ReferenceError: localStorage is not defined in Utils folder in nextjs

I am Trying to encrpty my localstorage data, it encrypted but it throws error.

MY code (./src/utils/secureLocalStorage.js)

import SecureStorage from 'secure-web-storage'
import CryptoJS from 'crypto-js'

const SECRET_KEY = process.env.REACT_APP_SECRET_KEY

let secureLocalStorage = null

try {
   secureLocalStorage = new SecureStorage(localStorage, {
   hash: function hash(key) {
   key = CryptoJS.SHA256(key, SECRET_KEY).toString()
   return key
},
encrypt: function encrypt(data) {
  data = CryptoJS.AES.encrypt(data, SECRET_KEY).toString()
  return data
},
decrypt: function decrypt(data) {
  try {
    data = CryptoJS.AES.decrypt(data, SECRET_KEY).toString(
      CryptoJS.enc.Utf8
    )
    return data
  } catch (error) {
    console.error('Error decrypting data:', error)
    return null
  }
},
})
} catch (error) {
  console.error('localStorage is not available:', error)
 }

export default secureLocalStorage

My error:
it comes in my terminal

enter image description here

how to create a horizontal photo containor by using html and css

I create a div for image along with text summary overflow container. what to do to not make it overflow

<div class="books-1" style="width:80% ;height:30%;; background-color: rgba(21, 18, 18, 0.8); border-radius: 17px;border: 2px solid;border-color: purple; margin: 2%;">
  <div class="book">

    <div class="book-info" style="background-color: rgba(0, 0, 0, 0.6) ; color:rgba(255, 255, 255, 0.721);margin: 4% 4% 4% 4%;border-radius: 5px;">
      <a href="  #####novel url" target="_blank" style="text-decoration: none;">
        <h3 style="padding: 4%;color: white;">Harry Potter and the Philosopher's Stone</h3>
      </a>
      <div class="summary" style="text-overflow: ellipsis; background-color: rgba(21, 18, 18, 0.584);width:60%;white-space: nowrap;overflow: hidden; margin: 2%;padding: 2%; color: white;"><a href="  #####novel url" target="_blank" style="text-decoration: none;color: white; width: 40%;">bhyxtxyrcyrcccfxxfcccccccccccxccccccccccccccccccccccccccccccccccccccccccccccccf</a></div>
      <p style="padding:1%;width:40%;">by J.K. Rowling</p>
      <div class="rating" style="width: 40%;">
        <span>⭐</span>
        <span>⭐</span>
        <span>⭐</span>
        <span>⭐</span>
        <span>⭐</span>
      </div>
      <div style="width: 35%; float: right; line-height: normal;"><img src="lib1b1.jpg" style="width: 60%;height: 100%;border-radius: 10px;size:200%;"></div>

      <button style="padding: 3%; margin:3%;border-radius:8cap;background-color:rgb(165, 62, 224);"><a href="https://www.amazon.in/Harry-Potter-Philosophers-Stone-Rowling/dp/1408855658/ref=sr_1_1?dchild=1&keywords=harry+potter&qid=1621514113&sr=8-1" target="_blank" style="color: white; text-decoration: none">Read Novel</a></button>
      <button style="padding: 3%;margin:3%; border-radius:8cap;background-color:rgb(165, 62, 224);"><a href="review url" target="_blank" style="color: white; text-decoration: none">Read Review</a></button>
    </div>


  </div>
</div>

Auto focus and maxlength for type number

I have a program that will skip to the next field after you enter the maximum allowed in the previous field. The input maxlength attribute does not work for type=”number”. Therefore, I have a javascript to make sure the maxlength is followed and only numerics are allowed.

<form action="myprogram.htm" method="post" name="myform">
<input type="number" size="5" maxlength="2" name="num1" onkeypress="return isNumberKey(event);" required>
<input type="number" size="5" maxlength="2" name="num2" onkeypress="return isNumberKey(event);" required>
<input type="number" size="5" maxlength="2" name="num3" onkeypress="return isNumberKey(event);" required>
</form>

<script type="text/javascript">
$("input").bind("input", function() {
    var $this = $(this);
    setTimeout(function() {
        if ( $this.val().length >= parseInt($this.attr("maxlength"),10) )
            $this.next("input").focus();
    },0);
});

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
</script>

However, there are three problems with this that I can’t seem to solve.

  1. The maxlength works for the first two fields, num1 and num2. But the third field can enter more than 2! Not sure why this is happening.
  2. If the 3 fields are already filled in e.g. 11, 22, 33. If you move to the first field and overwrite it with the number 555, it will jump to the second field 22 and add the third “5” in the second field at the end of 22. So you will end up with 225. It seems the javascript is not able to enforce the maxlength in this case.
  3. When you click on the first field “11” and try to use the up and down arrow to increase or decrease the number. The focus/highlight jumps to the next field 22 while you are increasing or decreasing the first field. I know the first field has reached the maxlength of two, but my cursor is still on the first field’s arrow.

Is there any way to fix these? Thanks in advance.

How can I display this overflowing table so that it stays within its parent div?

I’m not sure if I am allowed to post a link to the webpage instead of the code, but I think it will be easier to see the problem in action, and I’m sure you all know how to view the code in the browser’s debugger…

https://redditstatsbot.com/

When you select a short table, everything is fine. But when you select a huge table, the table overflows out of the div and I lose the footer. How can I keep everything stationary and just scroll through the table instead of scrolling down on the web page?

Mapbox – Collapsible Sidebar instead of Popup Message

Trying to implement collapsible side bars instead of using Mapbox built in Popup boxes for messages.

Had a go and built upon this and this thread.

My attempt can be found here, Javascript below:

// TO MAKE THE MAP APPEAR YOU MUST
    // ADD YOUR ACCESS TOKEN FROM
    // https://account.mapbox.com
    mapboxgl.accessToken = 'pk.eyJ1Ijoibml0dHlqZWUiLCJhIjoid1RmLXpycyJ9.NFk875-Fe6hoRCkGciG8yQ';
    const map = new mapboxgl.Map({
        container: 'map',
        // Choose from Mapbox's core styles, or make your own style with Mapbox Studio
        style: 'mapbox://styles/mapbox/streets-v12',
        center: [-77.04, 38.907],
        zoom: 11.15
    });

    map.on('load', () => {
        map.addSource('places', {
            // This GeoJSON contains features that include an "icon"
            // property. The value of the "icon" property corresponds
            // to an image in the Mapbox Streets style's sprite.
            'type': 'geojson',
            'data': {
                'type': 'FeatureCollection',
                'features': [
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Make it Mount Pleasant</strong><p><a href="http://www.mtpleasantdc.com/makeitmtpleasant" target="_blank" title="Opens in a new window">Make it Mount Pleasant</a> is a handmade and vintage market and afternoon of live entertainment and kids activities. 12:00-6:00 p.m.</p>',
                            'icon': 'theatre'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.038659, 38.931567]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Mad Men Season Five Finale Watch Party</strong><p>Head to Lounge 201 (201 Massachusetts Avenue NE) Sunday for a <a href="http://madmens5finale.eventbrite.com/" target="_blank" title="Opens in a new window">Mad Men Season Five Finale Watch Party</a>, complete with 60s costume contest, Mad Men trivia, and retro food and drink. 8:00-11:00 p.m. $10 general admission, $20 admission and two hour open bar.</p>',
                            'icon': 'theatre'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.003168, 38.894651]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Big Backyard Beach Bash and Wine Fest</strong><p>EatBar (2761 Washington Boulevard Arlington VA) is throwing a <a href="http://tallulaeatbar.ticketleap.com/2012beachblanket/" target="_blank" title="Opens in a new window">Big Backyard Beach Bash and Wine Fest</a> on Saturday, serving up conch fritters, fish tacos and crab sliders, and Red Apron hot dogs. 12:00-3:00 p.m. $25.grill hot dogs.</p>',
                            'icon': 'bar'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.090372, 38.881189]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Ballston Arts & Crafts Market</strong><p>The <a href="http://ballstonarts-craftsmarket.blogspot.com/" target="_blank" title="Opens in a new window">Ballston Arts & Crafts Market</a> sets up shop next to the Ballston metro this Saturday for the first of five dates this summer. Nearly 35 artists and crafters will be on hand selling their wares. 10:00-4:00 p.m.</p>',
                            'icon': 'art-gallery'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.111561, 38.882342]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Seersucker Bike Ride and Social</strong><p>Feeling dandy? Get fancy, grab your bike, and take part in this year's <a href="http://dandiesandquaintrelles.com/2012/04/the-seersucker-social-is-set-for-june-9th-save-the-date-and-start-planning-your-look/" target="_blank" title="Opens in a new window">Seersucker Social</a> bike ride from Dandies and Quaintrelles. After the ride enjoy a lawn party at Hillwood with jazz, cocktails, paper hat-making, and more. 11:00-7:00 p.m.</p>',
                            'icon': 'bicycle'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.052477, 38.943951]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Capital Pride Parade</strong><p>The annual <a href="http://www.capitalpride.org/parade" target="_blank" title="Opens in a new window">Capital Pride Parade</a> makes its way through Dupont this Saturday. 4:30 p.m. Free.</p>',
                            'icon': 'rocket'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.043444, 38.909664]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Muhsinah</strong><p>Jazz-influenced hip hop artist <a href="http://www.muhsinah.com" target="_blank" title="Opens in a new window">Muhsinah</a> plays the <a href="http://www.blackcatdc.com">Black Cat</a> (1811 14th Street NW) tonight with <a href="http://www.exitclov.com" target="_blank" title="Opens in a new window">Exit Clov</a> and <a href="http://godsilla.bandcamp.com" target="_blank" title="Opens in a new window">Gods’illa</a>. 9:00 p.m. $12.</p>',
                            'icon': 'music'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.031706, 38.914581]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>A Little Night Music</strong><p>The Arlington Players' production of Stephen Sondheim's  <a href="http://www.thearlingtonplayers.org/drupal-6.20/node/4661/show" target="_blank" title="Opens in a new window"><em>A Little Night Music</em></a> comes to the Kogod Cradle at The Mead Center for American Theater (1101 6th Street SW) this weekend and next. 8:00 p.m.</p>',
                            'icon': 'music'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.020945, 38.878241]
                        }
                    },
                    {
                        'type': 'Feature',
                        'properties': {
                            'description':
                                '<strong>Truckeroo</strong><p><a href="http://www.truckeroodc.com/www/" target="_blank">Truckeroo</a> brings dozens of food trucks, live music, and games to half and M Street SE (across from Navy Yard Metro Station) today from 11:00 a.m. to 11:00 p.m.</p>',
                            'icon': 'music'
                        },
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [-77.007481, 38.876516]
                        }
                    }
                ]
            }
        });
        // Add a layer showing the places.
        map.addLayer({
            'id': 'places',
            'type': 'symbol',
            'source': 'places',
            'layout': {
                'icon-image': ['get', 'icon'],
                'icon-allow-overlap': true
            }
        });

        // When a click event occurs on a feature in the places layer, open a popup at the
        // location of the feature, with description HTML from its properties.
        map.on('click', 'places', (e) => {
            // Copy coordinates array.
            const coordinates = e.features[0].geometry.coordinates.slice();
            const description = e.features[0].properties.description;

            // Ensure that if the map is zoomed out such that multiple
            // copies of the feature are visible, the popup appears
            // over the copy being pointed to.
            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
            }

            toggleSidebar('left')
            $(".sidebar-content").empty();
            $(".sidebar-content").append(description)

        });

        // Change the cursor to a pointer when the mouse is over the places layer.
        map.on('mouseenter', 'places', () => {
            map.getCanvas().style.cursor = 'pointer';
        });

        // Change it back to a pointer when it leaves.
        map.on('mouseleave', 'places', () => {
            map.getCanvas().style.cursor = '';
        });
    });
    
    function toggleSidebar(id) 
    {

        var elem = document.getElementById(id);
        var classes = elem.className.split(' ');
        var collapsed = classes.indexOf('collapsed') !== -1;

        var padding = {};

        if ( collapsed ) 
        {

            // Remove the 'collapsed' class from the class list of the element, this sets it back to the expanded state.
            classes.splice(classes.indexOf('collapsed'), 1);

            padding[id] = 260; // In px, matches the width of the sidebars set in .sidebar CSS class
            map.easeTo({
                padding: padding,
                duration: 1000 // In ms, CSS transition duration property for the sidebar matches this value
            });

        } 

        else 
        {

            padding[id] = 0;
            // Add the 'collapsed' class to the class list of the element
            classes.push('collapsed');

            map.easeTo({
                padding: padding,
                duration: 1000
            });

        }

        // Update the class list on the element
        elem.className = classes.join(' ');

    }

So clicking on the points opens up the sidebar, but when I click on another point, while the sidebar is open, it toggles the sidebar instead of updating the message.

How do I:

  • Update the toggle function so that if it is open, and another point is clicked, the sidebar remains open, but the content is updated
  • Still enable the search function (top left), so that when the side bar is open, users can still search. I suspect this is to do with the height of the sidebar, blocking access to the search bar, but I can’t get it all to work

Also, the inspector is throwing the following error:
“The map container element should be empty, otherwise the map’s interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead.” – is this something I can ignore? It’s because the sidebar div currently sits in the Mapbox div.

Script don’t load

i have this little problem on my html project. this is the principal html structure:

<div class="btn_disp_container">
          <button class="btn_disp" value="servicios-propiedades-php">Inscripción de      propiedades</button>
          <button class="btn_disp" value="servicios-comercio-php">Inscripción de comercio</button>
          <button class="btn_disp" value="servicios-civiles-php">Inscripción de Soc. Civiles</button>
          <button class="btn_disp" value="servicios-otros-php">Otros Servicios</button>
        </div>
        <div class="display_container">
          <div id="transition" class="transition" data-visible="false">
            <!-- Transicion del contenido -->
          </div> 
          <div id="display">
            <!-- Display de todo el contenido -->
          </div>
        </div>

what i want to do is to load content from other file (like php) in the div with the ‘display’ id, so i made this js:

const btn_display = document.querySelectorAll('.btn_disp');

for (const btn of btn_display) {
    btn.addEventListener('click', displayHtml);
}

function displayHtml() { // Carga de informacion al display
    const transition = document.getElementById('transition');
    const visible = transition.getAttribute('data-visible');

    if (visible === 'false') { // Verifica que no este activada la transición
        transition.setAttribute('data-visible', true);
        const btn = this;

        const [folder, file, type] = this.getAttribute('value').split('-'); 
        
        let route;
        if(type === undefined){
            route = `/RPPyC/pages/disp/${folder}/${file}.html`;
        }else {
            route = `/RPPyC/pages/disp/${folder}/${file}.${type}`;
        }

        const display = document.getElementById('display');

        transition.classList.add('transition-moving');
        enableButton(btn); 

        checkRoute(route)
            .then(() => {
                setTimeout(() => {
                    enableBack(display);
                    let xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            display.innerHTML = xhr.responseText;
                        }
                    };
                    xhr.open('GET', route, true);
                    xhr.send();
        
                }, 1500);
            })
            .catch(() => {
                setTimeout(() =>{
                    enableBack(display);
                    display.innerHTML= '<div class="nosotros_info_cont2"><p>¡Surgió un problema con la ruta! Verifica que coincida el valor del botón con la ruta del archivo (Carpeta-Archivo)</p></div>'
                }, 1500);
            })
            .finally(() => {
                setTimeout(() => {
                    transition.classList.remove('transition-moving');
                    transition.setAttribute('data-visible', false);
                }, 3000) 
            });
    }else{
    }
}

function checkRoute(route){ // verifica si existe el archivo en la ruta que se cargará en el display
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4){
                if(xhr.status == 200){
                    resolve();
                }else{
                    reject();
                }
            }
        };
        xhr.open('HEAD', route, true);
        xhr.send();
    });
}

function enableBack(display) {
    display.classList.add('display-active');
}

function enableButton(btn) {
    for (const btn of btn_display) {
        btn.classList.remove('btn_disp-active');
    }
    btn.classList.add('btn_disp-active');
}

i dont think its the best code, but it works, it charges the content in the div :).
the file that loads to the div looks like this:


<div class='servicios_info_cont'>
    <div class='servicios_text_cont'>
        <h1>Inscripción de propiedades</h1>
        <h5>Requisitos:</h5>
        <p>1 . Presentar Escritura Pública</p>
        <p>2 . Certificado de Libertad de Gravamen</p>
        <p>3 . Certificado de valor Fiscal o Catastral (vigencia de 90 días)</p>
        <p>4 . Certificado de solvencia de impuesto predial (vigencia de 90 días)</p>
        <p>5 . Certificado de solvencia de Agua Potable</p>
        <p>6 . Comprobante Domiciliario Catastral (CDC)</p>
        <p>7 . Aviso de translado de dominio e ISABI</p>
        <p>8 . ISR (en caso de que cause)</p>
        <p>9 . Pago de derecho de inscripción a inmuebles</p>
        <p>10 . Pago de derecho de fojas de Testimonio</p>
    </div>
    <div class='servicios_table_cont'>
        <div class='servicios_calc_header'>
            <p id='calc_title' class='servicios_calc_title' onclick='saludo()'>Calcular pago de derechos de fojas de Testimonio</p>
            <div class='servicios_calc_container'>
                <div class='servicios_calc'>
                    <p>Introduce la cantidad de fojas</p>
                    <input type="text" placeholder='Solo números'>
                    <button>Calcular</button>
                </div>
                <div class='servicios_calc_total'>
                    <p>Costo: <span>$67.09<span></p>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        function saludo(){
        console.log('Hola');
        }
    });
</script>

and here is the problem, it loads everything from this file except the ‘script’ tag (
I used it because it doesn’t load it with the ‘src’ attribute either) and i dont know why.
If i click the button with the ‘onclick’ function (i also used it for practical purposes), it says its not defined.

I tried almost everything I had in mind So I would greatly appreciate the help and also if you have any advice to improve the code and optimize it it would be very helpful.