not adjusting itself to bottom of menu

I have created a menu of nested ul. The problem is, when I add a second nested ul, the last li element among the first group of list elements doesn’t adjust it’s height from the top of the page to account for the height of the second ul(‘.sub-2’). It appears to the left but not below the ul. How do I get the last link (‘.last-link’) to account for the height of the second ul so that it appears below the ul.

$( document ).ready(function() {
    

$('#submen-1').on('click', function(e) {
        $('.sub-1').toggleClass("active");
        e.stopPropagation();
    })
 $('#submen-2').on('click', function() {

        if($('.sub-2').hasClass("active")) {
            $('.sub-2').removeClass("active");
        } else {
            $('.sub-2').addClass("active");
        }

    })

});
* {
    box-sizing: border-box;
}
body {
    height: 100vh;
}
nav {
    height: 10vh;
}
ul {
    list-style-type: none;
}
.sub-1 {
    height: 0px;
    visibility: hidden;
}

/* #submen-1:hover + .sub-1 {
    height: 55px;
    visibility: visible;
} */
.sub-2 {
    height: 0px;
    visibility: hidden;
}
/* #submen-2:hover + .sub-2 {
    height: 55px;
    visibility: visible;
}  */

.active {
    height: 55px;
    visibility: visible;
} 

.height {
    display: block;
    position: relative;
    top: 55.5px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Dropdown Menu Bar</title>
      <link rel="stylesheet" href="style.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
      <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
      <script src="https://kit.fontawesome.com/36947df53d.js" crossorigin="anonymous"></script>
      
    </head>
   <body>
      <nav>
          <a href="#" id="btn"><i class="fa-solid fa-bars"></i></a>
          
          <ul class="main">
              <li><a href="contact.html">Link</a></li>
              <li><a href="#">Link</a></li>
              <li><a href="#" id="submen-1">Sub</a>
                <ul class="sub-1">
                    <li><a href="#">Link</a></li>
                    <li><a href="#">Link</a></li>
                    <li><a href="#" id="submen-2">Sub-2</a>
                        <ul class="sub-2">
                            <li><a href="#">Link</a></li>
                            <li><a href="#">Link</a></li>
                            <li><a href="#">Link</a></li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li><a href="#" id="last-link">Last Link</a></li>
        
          </ul>
        
      </nav>
      <script src="script.js"></script>
   </body>
</html>

Performance issues with jspdf + html2canvas if there are many pages

const data = document.getElementById('containerDiv')!;
html2canvas(data, {
  removeContainer: false
}).then((canvas:any) => {
  const imgWidth = 208;
  const pageHeight = 295;
  const imgHeight = (canvas.height * imgWidth) / canvas.width;
  let heightLeft = imgHeight;
  let position = 0;
  heightLeft -= pageHeight;
  const doc = new jspdf('p', 'mm');
  doc.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
  while (heightLeft >= 0) {
    position = heightLeft - imgHeight;
    doc.addPage();
    doc.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
    heightLeft -= pageHeight;
  }
  doc.save('test.pdf');
});

Am facing performance issues with html2Canvas if there are multiple pages to render. Browser takes more time to download pdf and it get freezed.

Convert Excel math formula to javascritp

=ROUND(IF(A6>40000,(IF((A60.0215)<950,950,(A60.0215))),IF(A6>30000,(IF((A60.0235)<760,760,(A60.0235))),IF(A6>20000,(IF((A60.025)<560,560,(A60.025))),IF(A6>10000,(IF((A60.0275)<300,300,(A60.0275))),300))))(D6/365)+IF(E6=”yes”,70,0)+IF(F6=”yes”,50,0)+IF(G6=”yes”,10,0)+IF(H6=”yes”,30,0)+IF(I6=”yes”,20,0)+IF(J6=”yes”,IF(A6>40000,A60.0215,IF(A6>30000,A60.0235,IF(A6>20000,A60.025,IF(A6>12000,A60.0275,350))))(D6/365*0.15),0),-1)

D6=(C6-B6)-1

=ROUND(L6-(L6*K6),-1)

Question regarding useToggle(custom hook) vs useState hook in react

Below code is a custom Hook called useToggle from a website, it’s defined as a custom hook that can be useful when showing/hiding a modal but I don’t understand why to go through such code for such a simple feature. Isn’t it better to just use useState()

useToggle custom hook

import { useCallback, useState } from 'react';
// Usage
function App() {
    // Call the hook which returns, current value and the toggler function
    const [isTextChanged, setIsTextChanged] = useToggle();
    
    return (
        <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button>
    );
}
// Hook
// Parameter is the boolean, with default "false" value
const useToggle = (initialState = false) => {
    // Initialize the state
    const [state, setState] = useState(initialState);
    
    // Define and memorize toggler function in case we pass down the component,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback(() => setState(state => !state), []);
    
    return [state, toggle]
}

Just using normal useState()

const [shouldDisplayModal, setShouldDisplayModal] = useState(false);

<>
    {shouldDisplayModal && (
      <Modal>
        <ModalContent
          modalText={messageContent}
          primaryButtonText={buttonText}
          secondaryButtonText={NO_MESSAGE}
          modalIconState={modalIconState}
          handleClick={toggleSaveModal}
        />
      </Modal>
    )}
        <Button handleClick={toggleSaveModal} mainButton={false}>
          Save
        </Button>
        <Button handleClick={togglePublishModal} mainButton={true}>
          Publish
        </Button>

  </>

change password not save in database

I am trying to update details of user,name, email its work but in password is not updated.not any error show but whats the issue in there not show any error then why its not updated
This is controller code and validation of password and confirm password

 $request->validate([
        'name' =>'required|min:4|string|max:255',
        'email'=>'required|email|string|max:255',
        'current_password' => 'required',
      'password' => 'required|string|min:6|confirmed',
      'password_confirmation' => 'required',
    ]);
    $user =Auth::user();
    $user->name = $request['name'];
    $user->email = $request['email'];
      if (!Hash::check($request->current_password, $user->password)) {
        return back()->with('error', 'Current password does not match!');
    }

    $user->password = Hash::make($request->password);
    $user->save();

THis is blade file

<form action="{{route('home')}}" method="POST">
                    @csrf
                       <div class="form-group">
                           <label for="name"><strong>Name:</strong></label>
                           <input type="text" class="form-control" id ="name" name="name" value="{{Auth::user()->name}}">
                       </div>
                        <div class="form-group">
                           <label for="email"><strong>Email:</strong></label>
                           <input type="text" class="form-control" id ="email" value="{{Auth::user()->email}}" name="email">
                       </div>
                       <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">Current Password</label>
                            <div class="col-md-6">
                                <input type="password" class="form-control @error('current_password') is-invalid @enderror" name="current_password" autocomplete="current_password">
                                @error('current_password')
                                  <span class="invalid-feedback" role="alert">
                                      <strong>{{ $message }}</strong>
                                  </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">New Password</label>
                            <div class="col-md-6">
                                <input type="password" class="form-control @error('password') is-invalid @enderror" name="password" autocomplete="password">
                                @error('password')
                                  <span class="invalid-feedback" role="alert">
                                      <strong>{{ $message }}</strong>
                                  </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">Password Confirmation</label>
                            <div class="col-md-6">
                                <input type="password" class="form-control @error('password_confirmation') is-invalid @enderror" name="password_confirmation" autocomplete="password_confirmation">
                                @error('password_confirmation')
                                  <span class="invalid-feedback" role="alert">
                                      <strong>{{ $message }}</strong>
                                  </span>
                                @enderror
                            </div>
                        </div>
                        <button class="btn btn-primary" type="submit">Update Profile</button>
                   </form>

Bootstrap 5 container sizes not maching documentation

I am learning Bootstrap 5 (familiar with coding, but new at web technologies).

I am making some HTML documents to learn how bootstrap behaves.

Today I was working on “containers” when I noticed they are behaving a little bit different than the documentation says.

Container sizes are not the same as in the documentation. Here is an example:

enter image description here

I know this is not a critical difference but… why is this happening?

I am using JavaScript functions to update those indicators


function getWindowWidth(){
    return window.innerWidth;
}

function updateContainerWidthText(className){
    let indicator = document.getElementById("element-width-indicator-" + className)
    let container = indicator.parentElement;
    let width = container.clientWidth; 
    indicator.innerText = `Container width: ${width}px`;
    
}

function updateDocumentWidthText(){
    let width = getWindowWidth();
    let indicator = document.getElementById("document-width-indicator");
    indicator.innerText = `Document width: ${width}px` ;
}

function updateSize(){
    
    updateDocumentWidthText();
    updateContainerWidthText("container");
    updateContainerWidthText("container-sm");
    updateContainerWidthText("container-md");
    updateContainerWidthText("container-lg");
    updateContainerWidthText("container-xl");
    updateContainerWidthText("container-xxl");
    updateContainerWidthText("container-fluid");
    


}

updateSize();

window.addEventListener("resize", updateSize);

And the HTML code is this


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
    

    <title>Document</title>
</head>
<body>

    


    <h1>Container demo</h1>

    <div id="document-width-indicator"> indicator </div>
    
    <div class="container border "> 
        <h2> container</h2>
        <br>
        <div id="element-width-indicator-container"> indicator </div>
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 540px </li>
            <li> <b>Medium:</b> &gt= 768px = 720px  </li>
            <li> <b>Large:</b> &gt= 992px = 960px </li>
            <li> <b>X-Large:</b> &gt= 1200px = 1140px </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 1320px </li>
        </ul>
    </div>

    <div class="container-sm border "> 
        <h2> container-sm</h2>
        <br>
        <div id="element-width-indicator-container-sm"> indicator </div>
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 540px </li>
            <li> <b>Medium:</b> &gt= 768px = 720px  </li>
            <li> <b>Large:</b> &gt= 992px = 960px </li>
            <li> <b>X-Large:</b> &gt= 1200px = 1140px </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 1320px </li>
        </ul>
    </div>
    <div class="container-md border "> 
        <h2> container-md</h2>
        <br>
        <div id="element-width-indicator-container-md"> indicator </div>
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 100% </li>
            <li> <b>Medium:</b> &gt= 768px = 720px  </li>
            <li> <b>Large:</b> &gt= 992px = 960px </li>
            <li> <b>X-Large:</b> &gt= 1200px = 1140px </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 1320px </li>
        </ul>
    </div>
    <div class="container-lg border "> 
        <h2> container-lg</h2>
        <br>
        <div id="element-width-indicator-container-lg"> indicator </div>
        <br>
        Es la opcion usada habitualmente.
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 100% </li>
            <li> <b>Medium:</b> &gt= 768px = 100%  </li>
            <li> <b>Large:</b> &gt= 992px = 960px </li>
            <li> <b>X-Large:</b> &gt= 1200px = 1140px </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 1320px </li>
        </ul>
    </div>
    <div class="container-xl border "> 
        <h2> container-xl</h2>
        <br>
        <div id="element-width-indicator-container-xl"> indicator </div>
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 100% </li>
            <li> <b>Medium:</b> &gt= 768px = 100%  </li>
            <li> <b>Large:</b> &gt= 992px = 100% </li>
            <li> <b>X-Large:</b> &gt= 1200px = 1140px </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 1320px </li>
        </ul>
    </div>
    <div class="container-xxl border "> 
        <h2> container-xxl</h2>
        <br>
        <div id="element-width-indicator-container-xxl"> indicator </div>
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 100% </li>
            <li> <b>Medium:</b> &gt= 768px = 100%  </li>
            <li> <b>Large:</b> &gt= 992px = 100% </li>
            <li> <b>X-Large:</b> &gt= 1200px = 100% </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 1320px </li>
        </ul>
    </div>

    <div class="container-fluid border "> 
        <h2>container fluid</h2> 
        <br>
        <div id="element-width-indicator-container-fluid"> indicator </div>
        <br>
        Abarca todo el ancho de la pantalla.
        <br>
        <ul>
            <li> <b>Extra small:</b> &lt 576px = 100% </li>
            <li> <b>Small:</b> &gt= 576px = 100% </li>
            <li> <b>Medium:</b> &gt= 768px = 100%  </li>
            <li> <b>Large:</b> &gt= 992px = 100% </li>
            <li> <b>X-Large:</b> &gt= 1200px = 100% </li>
            <li> <b>XX-Large:</b> &gt= 1400px = 100% </li>
        </ul>
    </div>


    <!-- index.js -->
    <script src = "js/index.js"></script>

    
</body>
</html>

TypeScript: Can’t extend one interface from another

export interface IMStorage {
  isArray: <T>(a: T) => boolean;
  push: <T>(path: string, value: string) => T;
  get: <T>(path: string, defaultValue?: $TSFixMe) => T;
  set: <T>(path: string, value: $TSFixMe) => T;
  isEmpty: (path: string) => boolean;
}

Got a problem right here, while trying to extend one interface from another:

export interface IMStorageExtended extends IMStorage {
  [x: string]: string | AxiosInstance | { [x: string]: never[] } | null;
}

The issue is:

Property 'get' of type '<T>(path: string, defaultValue?: any) => T' is not assignable to 'string' index type 'string | AxiosInstance | { [x: string]: never[]; } | null'.

Label for hidden date input not working on Chrome

I have a date input and I want it to have a placeholder, so I added a label and a display none.
I have this code:

document.querySelector("#date").onchange = (e) => {
  document.querySelector("#datelabel").innerHTML = e.target.value;
}
#datelabel {
    padding: 16px;
    border-radius: 15px;
    border: 2px solid rgba(0, 0, 0, 0.8);
    outline: none;
    font-size: 20px;
    transition: .2s;
    width: 200px;
    display: block;
}
<input type="date" name="date" id="date" style="display:none;">
<label class="input" for="date" style="color:var(--text);" id="datelabel">Date</label>

It works fine on Firefox, but not on Chrome.
If I remove the display of none of the input, it works, but I don’t want the real input to be visible.
I tried to set a height and width to 0, an overflow: hidden, to remove the paddings and margins but it created a mess in the display of my page, so I want to keep the display of none and find another solution.

display a dropdown selector

hello i’m actually stuck on a problem where i would like to display a dropdown according to the user’s choice compared to another dropdown while in javascript so as not to reload the page to display the second

here’s my code (filename: addscore.php):

    <?php
$rolereq = "SELECT * FROM role";
$stm1 = getPDO()->query($rolereq);
$role = $stm1->fetchAll();

$champtopreq = "SELECT * FROM champ WHERE Role LIKE 'Top'";
$stm2 = getPDO()->query($champtopreq);
$champtop = $stm2->fetchAll();
?>
<form method="GET" action="?action=addscore" class="addscore">
    <label for="role">Choisie une lane :</label>
    <select name="role" id="role" onchange="display_champ();">
        <option value="none"></option>
        <?php
        foreach($role as $roles){
           echo "<option value='". $roles['Role'] . "'>". $roles['Role'] . "</option>";
        }
        ?>
    </select><br>
    <label for="champ">Choisie un Champions :</label>
    <select name="champ" id="champ">
        <option value="none"></option>
        <?php
        foreach($champtop as $champtops){
            echo "<option id='top' style='display: none;' value='". $champtops['Nom'] . "'>". $champtops['Nom'] . "</option>";
        }
        ?>
    </select>
    <script type="text/javascript" src="../../assets/display.js">

    </script>
</form>

Here’s the javascript(filename: display.js):

    function displaychamp() {
    var selectedrole = document.getElementById("role").value;
    if ( selectedrole == 'Top' ) {
        document.getElementById('top').style.display = "block";
    }
}

new Audio is stopped after pause (get ‘stalled’ event)

I use radio stream link.
After about 3-4 minutes radio playing I pause one and then after about 5-10 minutes I play radio again, then after 3-4 minutes radio is stopped.
I get event
console.log(‘stalled’, res):

isTrusted: true
bubbles: false
cancelBubble: false
cancelable: true
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
path: : {
crossOrigin: "anonymous"
currentSrc: "https://radiostreammingblablabla.ru/channel96.aacp"
  error: MediaError
code: 3
message: "PIPELINE_ERROR_DECODE: Failed to send audio packet for decoding: {timestamp=625406259 duration=46440 size=588 is_key_frame=1 encrypted=0}"
  }
returnValue: true
srcElement: null
target: null
timeStamp: 2193210.300000012
type: "stalled"

Event timeupdate is stopped also

App Vue:

// initialize 
state.audio             = new Audio()
state.audio.crossOrigin = "use-URL-credentials"
state.audio.src         = channel.stream_url
// ..........

// Pause 
state.audio.pause();
state.aTime             = state.audio.currentTime;
state.audio.currentTime = 0;
// .....

// Play
context.state.audio.play().then(() => {
if (context.state.aTime) {
  context.state.audio.currentTime = context.state.aTime;
}
// .....

// Events
context.state.audio.addEventListener('stalled', (res) => {
  console.log('stalled', res)
});

context.state.audio.addEventListener('timeupdate', (res) => {
  console.log('timeupdate', res)
});
// .....
 "dependencies": {
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/proxy": "^2.1.0",
    "@nuxtjs/router": "^1.6.1",
    "@nuxtjs/sentry": "^5.1.0",
    "@nuxtjs/style-resources": "^1.2.0",
    "axios": "^0.21.1",
    "core-js": "^2.6.5",
    "crypto-js": "^4.0.0",
    "fingerprintjs2": "^2.1.4",
    "firebase": "^7.6.0",
    "moment": "^2.29.1",
    "nuxt": "^2.4.0",
    "nuxt-sass-resources-loader": "^2.0.5",
    "vue-awesome-swiper": "^3.1.3",
    "vue-function-api": "^3.0.0-beta.0",
    "vue-select": "^3.2.0",
    "vue-slider-component": "^3.2.13",
    "vue2-touch-events": "^3.2.2"
  },
  "devDependencies": {
    "@babel/plugin-proposal-optional-chaining": "7.12.7",
    "@nuxt/typescript-build": "^0.6.1",
    "@nuxt/typescript-runtime": "^0.4.1",
    "crypto-js": "",
    "fs": "",
    "jasmine": "^3.3.0",
    "node-sass": "^4.13.1",
    "pug": "^2.0.3",
    "pug-plain-loader": "^1.0.0",
    "sass-loader": "^7.3.1"
  }

I really don’t understand what is wrong, help please.
P.S if I open radio link directly in browser tab, i don’t get this problem

Find content-length of gzip’ed fetch() response

I’m doing a large fetch() and I want to have a progress bar. When I return uncompressed content from the webserver, the following code works fine.

When I enable gzip on the webserver, the content-length reflects the compressed size (which is correct given the HTTP spec) and the stream that I’m reading gives me uncompressed data (which is correct according to the Fetch spec)… however the combination of these two correct behaviours means that my progress bar is useless (it reports “300% complete: loaded 1200KB [of uncompressed data] from a total of 400KB [of compressed data]”)

Is there any way to either measure “how much compressed data has been downloaded so far” (to compare against the content-length header) or “how long is the uncompressed data expected to be” (to compare against the uncompressed stream I’m reading)?

    fetch("http://example.com/bigdata.json")
        .then((response) => {
            if (!response.body) return;
            const reader = response.body.getReader();
            let download_done = 0;
            let download_size = parseInt(response.headers.get("content-length"));

            return new ReadableStream({
                start(controller) {
                    function push() {
                        reader.read().then(({ done, value }) => {
                            if (done) {
                                controller.close();
                                return;
                            }
                            if (value) {
                                download_done += value.byteLength;
                                report_progress(download_done, download_size);
                            }
                            controller.enqueue(value);
                            push();
                        });
                    }
                    push();
                },
            });
        })
        .then((stream) => {
            return new Response(stream, {
                headers: { "Content-Type": "text/json" },
            }).json();
        })
        .then(function (result) {
            console.groupCollapsed("api_request(bigdata.json)");
            console.log(result);
            console.groupEnd();
        })

How are image uploads done in Vue 3

I want to send text and an image to a blog post API endpoint that accept a text (required ) and an image ( optional ). I am able to POST a new blog post when I fill in a textarea only but unable to send an image in the POST body. Here’s the form fields

<label for="comment" class="sr-only">Write what's on your mind</label>

<textarea
    v-model="form.post"
    rows="3"
    name="comment"
></textarea>

<label>
  <input ref="file" type="file" v-on:change="onImageUpload(e)" />
</label>

In my script setup

<script setup>
    import { ref } from "vue";
    
    const form = ref({
      post: null,
      file: null
    });
    
    function onImageUpload() {
        console.log(file.value.files);
        // form.value.file = form.value.file[0]; 
        // console.log("selected file", form.value);
    }
</script>

This code returns the error below

Uncaught ReferenceError: file is not defined

How can I access the image file being uploaded and pass it along inside the form.value?

How to combine functions in ajax?

I understand this is a “dumb” question, but I tried to merge several functions with the same ajax calls that I want to integrate. but it causes a problem when I run code

Here below there are two functions that I want to combine

Example 1 Function Code

function getPostInfo(value, res, id, a) {
      var scrolltable = "";
      scrolltable = "info" == value ? res.content ? res.content.$t : "" : res[id].content ? res[id].content.$t : "";
      var body = $("<div>").html(scrolltable).find('a:contains("getProduct")').first();
      if (body.length) {
        body.replaceText(/([^{}]+(?=}))/g, "<em>$1</em>");
        body.find("em").replaceText("$", "%s");
        var el = body.text();
        var className = pikiShortcode(el, "price");
        var attr = pikiShortcode(el, "sale");
        var val = pikiShortcode(el, "free");
        var sortable = pikiShortcode(el, "icon");
        val = 0 != val ? val.toLowerCase().trim() : "no";
        sortable = 0 != sortable ? sortable.toLowerCase().trim() : "cart";
        a = [className = 0 != className ? '<span class="entry-price' + ("yes" == val ? " is-free" : "") + '">' + className.replace("%s", "$") + "</span>" : "", attr = 0 != attr && "yes" != val ? '<span class="entry-sale">' + attr.replace("%s", "$") + "</span>" : "", val];
      } else {
        a = false;
      }
      return a;
    }
    
    function getPosts(target, type, query, userId, callback) {
      userId = 0 != userId ? userId : "unlabeled";
      $.ajax({
        url: label = "info" != target ? "/feeds/posts/default/" + query + "?alt=json&max-results=1" : "/feeds/posts/default/" + query + "?alt=json&max-results=1",
        type: "GET",
        dataType: "json",
        cache: true,
        success: function (data) {
          var html;
          var points;
          var th_field = "";
          var res = "info" == type ? data.entry : data.feed.entry;
          if (res) {
            switch (type) {
              case "info":
                th_field = getPostMeta(points = getPostInfo(type, res), points[0], points[1]);
                break;
              default:
            }
          }
          switch (type) {
            case "info":
              if (0 != points) {
                target.find(".super-category").append("is-side" != userId ? th_field[0] : th_field[1]);
                target.addClass("ready");
              } else {
                target.addClass("error");
              }
              break;
            default:
          }
    
        }
      });
    }
    function getProductInfo(state, el) {
      el = state.data("id");
      if (null != el) {
        getPosts(state, "info", el);
      }
    }
   
      $(".index-posts-wrap .product, .PopularPosts .side-item").each(function() {
      getProductInfo($(this));
        });

Now I am trying to Combine the above Example 1 Function Code to Example 2 Function Code

Here is
Example 2 Function Code

function defaultCodeiki(parent, count, label, order) {
var furl = "",
    startIndex = Math.floor((Math.random() * count) + 1);
  if (label !== undefined) {
    if (label.match('recent')) {
      furl = '/feeds/posts/default?alt=json&max-results=' + count;
    } else if (label.match("random")) {
      furl = '/feeds/posts/default?alt=json&orderby=updated&start-index=' + startIndex + '&max-results=' + count;
    } else if (label.match("show")) {
      furl = '/feeds/comments/default?alt=json&max-results=' + count;
    } else if (!(label.match('random')) || !(label.match('recent'))) {
      furl = '/feeds/posts/default/-/' + label + '?alt=json&max-results=' + count;
    }
  }
  if (furl.length > 0) {
    $.ajax({
      type: 'GET',
      url: furl,
      cache: true,
      dataType: 'json',
      beforeSend: function (data) {
        switch (order) {
           case 'megamenu':
           parent.addClass("mega-menu");
           break;
       case "grid1":
            parent.html(beforeLoader()).parent().addClass('type-' + order + ' open-iki');
            break;
        }
      },
      success: function (data) {
        var htmltype = '';
        switch (order) {
          case 'megamenu':
            htmltype += '<div class="BiggerMenu"><div class="mega-boxs">';
            break;
           case 'grid1':
            htmltype += '<div class="grid-bottom">';
            break;
          default:
            htmltype += '<ul>';
            break;
        }


        var json = data.feed.entry;
        if (json != undefined) {
          for (var i = 0, feed = json; i < json.length; i++) {
            for (var j = 0; j < json[i].link.length; j++) {
              if (json[i].link[j].rel == "alternate") {
                link = json[i].link[j].href;
                break;
              }
            }
           var title = json[i].title.$t ? json[i].title.$t : pikiMessages.noTitle,
              author = json[i].author[0].name.$t,
              content = json[i].content.$t,
              data = getPostInfos(content),
          secondBusy = getPostMetas(data, data[0], data[1]),
              id = (id = json[i].id.$t) ? id.split("-").pop() : "",
              $content = $('<div>').html(content),
            if ('category' in json[i]) {
              if (json[i].category[0].term !== undefined) {
                var tag = json[i].category[0].term;
              }
            } else {
              var tag = 'Uncategorized';
            }
            
              var sort = '';
             if (json[i].media$thumbnail) {
              var $src = json[i].media$thumbnail.url
            } else {
              $src = noThumb;
            }

             var yt = getImageiki($src);
            switch (order) {
                 case 'grid1':
                htmltype += '<div class="bottom-posts product piki-l" data-id="' + id + '"><div class="bottom-img"><a class="post-filter-link ' + yt + '" href="' + link + '"><img class="snip-thumbnail" alt="' + title + '" data-src="' + $src + '"/></a></div><div class="super-category"><h2 class="entry-title" ><a href="' + link + '" title="' + title + '">' + title + '</a></h2>' + secondBusy[0] + '</div></div>';
                break;
              default:
                parent.html(beforeLoader()).parent().addClass('open-iki');
                htmltype += msgError();
                parent.parent().html(htmltype);
                break;
            }
          }
          sort += '</ul>';
          htmltype += sort;
        } else {
          switch (order) {
            case 'megamenu':
              htmltype = '<div class="BiggerMenu">' + msgError() + '</div>';
              break;
            default:
              htmltype = msgError();
              break
          }
        }
        switch (order) {
          case 'megamenu':
            htmltype += '</div></div>';
            parent.addClass(order).find(".BiggerMenu").replaceWith(htmltype);
            break;
          case 'grid1':
            parent.html(htmltype);
            htmltype += '</div></div>';
            break;
          default:
            htmltype += '</div>';
            parent.html(htmltype);
            break;
        }
         switch(order) {
     case "megamenu":
         parent.find("img.snip-thumbnail").lazyimg({onScroll:false});
       break;
     default:
       pikiLoveIt(parent.find('.piki-l'));
   }
      },
      error: function () {
        switch (order) {
          case 'megamenu':
            parent.append('<div class="BiggerMenu">' + msgError() + '</div>');
            break;
          default:
            parent.html(msgError());
            break
        }
      }
    });
  }
};

Does anybody advice me how I can combine Example 1 Function code to Example 2 Function code Any kind of help or suggestion is highly appreciated

how to send multi args to Django custom templates from JS code inside HTML template

I’m trying to use a custom template tag to run a specific function on a variable that I get in JS inside my HTML template.

here is a sample of what I tried :

python template tag

def calculate_km(value, arg):
    """
    Calculate the km from the source
    """
    args_list = eval(arg)
    layer_id = value
    return f"layer_id_is:{layer_id}, args_list:{args_list}"

then am using it inside my HTML js block like this :

const args_data = "[" + kmlEvent.featureData.id + "," + kmlEvent.latLng.lat + "," + kmlEvent.latLng.lng + "]";
console.log(`{{single_layer.id|calculate_km: ${args_data} }}`);

The problem here is in adding the JS variable inside the template tag , as you see using args_data inside the string that should return syntax for normal Django template so what is expected is that the console.log line renders as follows :

{{12|calculate_km:[12,Foo,123,456]}}

But the problem is that it is not reading the value of the variable args_data and it is being rendered as :

{{12|calculate_km: ${args_data}}}

and of course, that returns an error which is :

django.template.exceptions.TemplateSyntaxError: calculate_km requires 2 arguments, 1 provided

so it seems like not even reading the value of args_data