How to combine Tailwind and CSS Stylesheets in Next.js

I have a nextjs project (version 14.2.1 and using app folder) and I wanna combine combine Tailwind and CSS Stylesheets

Code in Button component

import classNames from 'classnames'
import styles from './index.module.css'

const Button = ({ children, className }) => {
  return <button className={classNames(styles.button, className)}>{children}</button>
}
export default Button

Code css for Button component

.button {
  @apply text-center
  text-red-500;
}

Code reference Button component above

import Button from '@/components/Common/Button'
import classNames from 'classnames'

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <Button className={classNames('text-yellow-300')}>Click me</Button>
    </main>
  )
}

I expect button “Click me” has text color is text-yellow-300 but button “Click me” actually has text color is text-red-500

How can I deal with it? Thanhs a lot!

Fitting images to the same height and scrolling sideways

I’m trying to make a basic portfolio site with some pictures and was aiming to make it all fit into a single view and scroll the images in from the side as the user scrolls. I also have images that are both portrait and others that are landscape and would like them all to be the same height, regardless of width. Getting the heights to line up led to some odd behavior with the scrolling where the side scrolling (done with js) stops working, and when manually scrolling sideways, the header moves along with it (which I can fix by changing the header from absolute to fixed).

Is there a better way to tackle this problem?

Here’s a demo: https://jsfiddle.net/nkbe579j/

Here’s the code, page 1 works with getting the images to fit how I wanted on both large and small screens (accomplished by setting max-w-none), but page 2 works with the scrolling code I set up (though on smaller screen sizes, the landscape pictures shrink to fit the screen width, which I don’t want). I can’t seem to get both to work in harmony.

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

<body class="">
    <div class="absolute top-4 bottom-4 h-12 w-full mb-3 z-20">
        <div class="absolute left-5">
            HEADER
        </div>
        <button class="absolute right-5" onclick="changePage()">Change Page</button>
    </div>

    <div class="absolute top-16 bottom-0 z-0" id="content-container">
        <div class="flex flex-row h-screen items-center overflow-y-hidden max-h-full image-container" id="page-1">
            Page 1
            <!-- Placeholder image links removed due to spam filter -->
            <img class="mr-1 max-w-none max-h-full" src="~portait-image~">
            <img class="mr-1 max-w-none max-h-full" src="~landscape-image~">
            <img class="mr-1 max-w-none max-h-full" src="~portait-image~">
            <img class="mr-1 max-w-none max-h-full" src="~landscape-image~">
            <img class="mr-1 max-w-none max-h-full" src="~portait-image~">
            <img class="mr-1 max-w-none max-h-full" src="~landscape-image~">
            <img class="mr-1 max-w-none max-h-full" src="~portait-image~">
            <img class="mr-1 max-w-none max-h-full" src="~landscape-image~">
        </div>

        <div class="flex flex-row h-screen items-center overflow-y-hidden max-h-full image-container hidden" id="page-2">
            Page 2
            <!-- Placeholder image links removed due to spam filter -->
            <img class="mr-1 max-h-full" src="~portait-image~">
            <img class="mr-1 max-h-full" src="~landscape-image~">
            <img class="mr-1 max-h-full" src="~portait-image~">
            <img class="mr-1 max-h-full" src="~landscape-image~">
            <img class="mr-1 max-h-full" src="~portait-image~">
            <img class="mr-1 max-h-full" src="~landscape-image~">
            <img class="mr-1 max-h-full" src="~portait-image~">
            <img class="mr-1 max-h-full" src="~landscape-image~">
        </div>
    </div>

    <script>
        function changePage() {
            document.querySelector('#page-1').classList.toggle('hidden');
            document.querySelector('#page-2').classList.toggle('hidden');            
        }

        addEventListener("wheel", (event) => {
            // ideally, I'll maintain the active element id and not have both of these here
            document.querySelector('#page-1').scrollLeft = document.querySelector('#page-1').scrollLeft - event.wheelDeltaY;
            document.querySelector('#page-2').scrollLeft = document.querySelector('#page-2').scrollLeft - event.wheelDeltaY;
        });
    </script>
</body>

</html>

humbarger icon on mobile wont open the navigation

I am building a simple wordpress theme and in the navigation when browser shrunk to mobile size the humbarger icon appears but it wont open the nav as expected. I tried a few codes and I cant seem to find out whats wrong. Any help would be appriciated. Since this is a wordpress I wasnt able to do fiddle here:

appd4b.com is the live demo


<header>
 <nav class="navigation" id="myTopnav">
    <div class="logo">
      <img src="https://appd4b.com/wp-content/uploads/2024/04/WEBD4B-removebg-preview.png" alt="Site Logo" width="15%" height="15%">
    </div>
    
    <ul class="menu-list">
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#portfolio">Project</a></li>
      <li><a href="#">Contact</a></li>
    </ul>

    <a href="javascript:void(0);" class="humbarger icon" onclick="toggleMenu()">
      <i class="fa fa-bars"></i>
    </a>
  </nav>
</header>

and then In js file I have

function toggleMenu() {
  var x = document.getElementById("myTopnav");
  if (x.className === "navigation") {
    x.className += " responsive";
  } else {
    x.className = "navigation";
  }
}

And Css is rather straight forward



.navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f8f8f8; /* Adjust as needed */
}

.logo {
  flex: 1;
}

.logo img {
  display: block;
  margin: 0 auto;
  max-width: 100%;
  height: auto;
}

.menu-list {
  flex: 1;
  display: flex;
  justify-content: center;
  list-style: none;
  padding: 0;
}

.menu-list li {
  margin: 0 10px;
}

.menu-list li a {
  text-decoration: none;
  color: #333; /* Adjust as needed */
}

.humbarger {
  display: none; /* Hide by default */
}

@media screen and (max-width: 768px) {
  .menu-list {
    display: none; /* Hide menu on smaller screens */
  }

  .humbarger {
    display: block; /* Show hamburger menu on smaller screens */
    cursor: pointer;
  }

  .bar {
    width: 25px;
    height: 3px;
    background-color: #333;
    margin: 5px 0;
  }

  .bar2 {
    width: 20px; /* Adjust to create hamburger effect */
  }
}
@media screen and (max-width: 600px) {
  .navigation .menu-list {
    display: none;
  }

  .navigation.responsive .menu-list {
    display: block;
  }
}


I was trying with javascirpt but if jquery is better I will do that

How make “Show More” button with Javascript and Flask For Loop in tables

I’m building an application for student consultation. In the admin tab I show the students who are registered through a table. However, I don’t want to display them all at once, because that will make the page look cluttered.
That’s why I want to display only 5 students and after clicking “Show all”, the rest of the students will be displayed in the table.

I saw some tutorials for implementation with javascript, I managed to implement it using a simple html list, but when I try to use it with tables it doesn’t work as expected.

With Lists I used this solution:

flask app:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/'])
def home():
    array= ['test-1', 'test-2', 'test-3', 'test-4', 'test-5', 'test-6']
    return render_template('home.html', array=array)

if __name__ == "__main__":
    app.run(debug=True)

HTML:

...
<ul>
      {% for item in array[:3] %}
        <li>{{ item }}</li>
      {% endfor %}

      <div class="show" style="display: none;">
        {% for item in lista[3:] %}
        <li>
          {{ item }}
        </li>
      {% endfor %}
      </div>
    </ul>

    <button class="buttonShow">Mostrar mais</button>
...

javascript:

<script>
      const buttonShow = document.getElementsByClassName("buttonShow")[0]
      const showItens = () => {
        document.getElementsByClassName("show")[0].style.display = "inline";
      }
      buttonShow.addEventListener('click', showItens)
    </script>

This works fine, I click in the button and the rest of the itens display.
I tried this same solution for the html tables, but the result was not as expected, instead of the students and their information appearing in new lines. All new rows appeared in a single table cell.

This is the table before I click the button:
enter image description here

And this is after I click the button:
enter image description here

The solution I tried to use for the tables was this:

Flask app:

@app.route('/admin')
@login_required
def admin():
    alunos = Aluno()
    users = User.query.all()
    admin = User.query.filter_by(id=current_user.id).first()
    if current_user.admin == 1:
        return render_template("admin.html", alunos=alunos, reversed=reversed)
    else:
        flash("You dont have access")
        return(redirect(url_for('home')))

Html:

<h2>New Students</h2>
          <table>
            <thead>
              <tr>
                <th>Nome</th>
                <th>Curso</th>
                <th>Idade</th>
                <th>Pagamento</th>
                <th>Bolsa?</th>
              </tr>
            </thead>


            <tbody>
              {%for aluno in reversed(alunos.query.all()[-5:])%}
              <tr>
                <td>
                  <a href="{{url_for('aluno', aluno_id=aluno.id)}}"
                    >{{aluno.nome}}</a
                  >
                </td>
                <td>{{aluno.curso}}</td>
                <td>{{aluno.idade}}</td>
                <td>
                  {% for pag in aluno.pagamento %} 
                    {% if pag.pagamento %} 
                      Pago 
                    {% else %} 
                      Não Pago 
                    {% endif %} 
                  {% endfor %}
                </td>
                <td>
                  {% if aluno.bolsa %}
                    Possui Bolsa
                  {% else %}
                    Não Possui
                  {% endif %}
                </td>
              </tr>
              {%endfor%}

              <tr class="itens-toShow" style="display: none;">
                  {%for aluno in reversed(alunos.query.all()[0:-5])%}
                    <td>
                        <a href="{{url_for('aluno', aluno_id=aluno.id)}}"
                          >{{aluno.nome}}</a
                        >
                      </td>
                      <td>{{aluno.curso}}</td>
                      <td>{{aluno.idade}}</td>
                      <td>
                        {% for pag in aluno.pagamento %} 
                          {% if pag.pagamento %} 
                            Pay
                          {% else %} 
                            not pay 
                          {% endif %} 
                        {% endfor %}
                      </td>
                      <td>
                        {% if aluno.bolsa %}
                          Have
                        {% else %}
                          Dont Have
                        {% endif %}
                      </td>
                  {%endfor%}
              </tr>
              

            </tbody>

          </table>

Javascript:

let itemToshow = document.getElementsByClassName("itens-toShow")[0];
let buttonShow = document.getElementsByClassName("mostrar-itens")[0];

const mostrarMaisAlunos = () => {
    itemToshow.style.display = 'block';
    
};

buttonShow.addEventListener('click', mostrarMaisAlunos);

What am I doing wrong?

How can I get my order hook to update in react js?

I am trying to update the values in my order hook. However, the values do not seem to be updating. I am fairly new to React and am not sure what I am doing wrong here. Any Ideas?

Here is my code:

const [order, setOrder] = useState({
    specBurger: "",
    protein: "",
    bread: "",
    toppings: "",
    sides: "",
    drinks: "",
    price: 0.00
})
const navigate = useNavigate();
const update = () => {
    setOrder((prev) => ({...prev,
        specBurger: specItemsString,
        protein: proteinItemsString,
        bread: breadItemsString,
        toppings: toppingsItemsString,
        sides: sideItemsString,
        drinks: drinkItemsString,
        price: price.toFixed(2),
    }));
}
const processOrder = async (e) =>{
    e.preventDefault();
    update();

    try{
        await axios.post('http://localhost:8800/ordered', order);
        navigate("/pages/Confirmation");
    }catch(err){
        console.log(err);
    }
}

I have tried not doing an update() function and just updating the values inside the processOrder() but that still didn’t work.

I also tried updating the values without using the (prev) => ({...prev, That did not work either.

Render page send data from mongodb to html it is not working

I am getting the data from mongodbd with success; However, when I send to html page returns the error “workData is not defined”. I am not using the app.js page to render.
I am using the ‘/api/time’, router to render and save data to db. When I try to send the workData getting from mongoose in the r_time.js and render the data using res.render(‘pages/punch_log’, {workData}), it returns the error “workData is not defined”. How should I render this data?

app.js

//import base routes
const baseRoutes = require('./routes/base_routes')
const { time } = require('console')
app.use('/', baseRoutes)
app.use('/post', baseRoutes)
app.use('/punch_log', baseRoutes)
app.use('/login', baseRoutes)
app.use('/punch', baseRoutes)

//Set the view Engine EJS
app.set('views','./views')
app.set('view engine', 'ejs')
//parse json bodies
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended:true}))
app.use('/api/time', timeRouter)

punch_log.ejs

  <main class="container">
            <h1>History Log</h1>
            <% workData.forEach(employee => { %>
            <div class="log">
                <p class="day" id="l-day"><%= workData.weekDay%> : <%= workData.day%></p>
                <p class="clock-in" id="l-clock-in">Clock In: 8:00</p>
                <p class="break-start" id="l-break-start">Break Start: 12:00</p>
                <p class="break-end" id="l-break-end">Break End: 13:00</p>
                <p class="clock-out" id="l-clock-out">Clock Out: 17:00</p>
                <p class="total-day" id="l-total-day">Total day: 7:00</p>
                <hr>
            </div>
           <% }) %>

punch_log.js

async function getIdFromEmployee(){
    console.log("function getIdFromEmployee", employeeId)
    const options = {
        method: 'get',
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ employeeId })
    }
    try{
        const response = await fetch('/api/time/punch_log', options)
        if(!response.ok){
            throw new Error(`HTTP error! Status: ${response.status}`)
        }
    }catch(error){
        console.error("Network error:", error.message);
    }
}

//window.onload = getIdFromEmployee
window.onload = function(){
    if(window.location.href.indexOf('/punch_log') > -1){
        getIdFromEmployee()
    }
}

r_time.js

//history log send data
router.get('/punch_log', async (req, res) => {
    const {employeeId} = req.body
    console.log("entered: ", employee)
   /* Punch.find({employeeId: employeeId}).then(employee => {
        console.log("fetch punch_log history worked: ", employee)
        res.render('pages/punch_log', {employee})
    })*/
    try{
        let name = ''
        let workData = await Punch.find({employeeId: employeeId})
        console.log('work data result: ', {workData})
        res.render('pages/punch_log', {workData})
    }catch(error){
        console.error("send work date error: ", error)
    }
})

How to use _gaq.push in Google Analytics 4

As Google Analytics has now updated to Google Analytics 4, I am wondering how do you configure a _gaq.push(). I am wanting to utilize an anti-adblock (BlockAdBlock.com) but still track it in Google Analytics.

On this website, under the Analytics Integration section it gives an example of

_gaq.push(['_trackEvent', 'BlockAdblock', 'Yes', undefined, undefined, true]);

However, all tutorials are outdated for the old Google Analytics. Wondering if someone could assist in helping me figure out how to set a _gaq.push()

Is not Descendants Always Rerendered

I am reading the React new documentation here, it said:

Here, the context value is a JavaScript object with two properties,
one of which is a function. Whenever MyApp re-renders (for example, on
a route update), this will be a different object pointing at a
different function, so React will also have to re-render all
components deep in the tree that call useContext(AuthContext).

For what said “so React will also have to re-render all components deep in the tree that call useContext(AuthContext)“, I wonder is that not so right. From what I tested, if a parent component call setState() method, the parent component along with all its children and children’s children, actually all descendants, is being rerendered.

The “have to rerender components deep in the tree that call useContext” seems not right to me, whatever a descendant calling a useContext or not, it is going to be rerendered. Is my understanding right or not?

Ensuring each table’s column dropdown filter can filter all other column dropdown filters without unwanted interactions

Is there a simple ‘filter all other dropdowns according to the one that triggered the ‘change’ event?

My goal: Build an excel-style ‘Autofilter’ dropdown for each column in a table. Filter each column’s dropdown options by those selected in the other columns.

The table has 3 columns: Category, Subcategory, Product.

I’m struggling to find a simple way to script ‘Filter all other dropdowns by this dropdown’, other than specifically mapping Column 1’s filter conditions to Columns 2 and 3, and likewise mapping Column 2’s filters to Columns 1 and 3 etc. This would have clear scaling issues.

The current approach overview is below (Note how it currently cascades from category => subcategory => product, but I aim to have all dropdowns being able to filter each other)

  1. Webpage loads =>

  2. populatedropdown() adds event listeners to all checkboxes =>

  3. EVENT: a checkbox ‘check’ value is changed =>

4a) call filtersubcategories() to modify available subcategory dropdown options according to category dropdown selections

AND

4b) call filterproducts() to do the same with available product dropdown options

(Disclaimer: yes, I’ve googled around and whilst there’s loads of advice about dropdown filters in JS (using react, for example), 1) it tends to be ‘directional’ (i.e., ‘cascade filters so column 1 filters column 2 but not vice versa). I can’t find anything relating to ensuring that the filtering in one dropdown filters all other available options in the table-if there’s any available materials/libraries to help, I’m all ears!)

I considered pasting the filterSubcategories() and filterProducts() (plus relevant event listeners) as snippets, but I figured there the rest of the script could be useful for
context.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Table with Filtering</title>
<style>
    /* Style for the table */
    table {
        border-collapse: collapse;
        width: 100%;
    }
    th, td {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
    }
    tr:nth-child(even) {
        background-color: #f2f2f2;
    }
    .filter-dropdown {
        position: relative;
        display: inline-block;
        margin-bottom: 10px;
    }
    .filter-dropdown-content {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 150px;
        box-shadow: 0 2px 4px 0 rgba(0,0,0,0.2);
        z-index: 1;
        padding: 10px;
    }
    .filter-dropdown-content label {
        display: block;
        margin-bottom: 5px;
    }
</style>
</head>
<body>
<h2>Data Table with Filtering</h2>
<div>
    <input type="text" id="categoryInput" onkeyup="filterTable()" placeholder="Filter by Category..">
    <input type="text" id="subcategoryInput" onkeyup="filterTable()" placeholder="Filter by Subcategory..">
    <input type="text" id="productInput" onkeyup="filterTable()" placeholder="Filter by Product..">
    <button onclick="resetFilters()">Reset Filters</button>
</div>

<table id="myTable">
  <thead>
    <tr>
      <th>
        <div class="filter-dropdown" onclick="toggleDropdown('categoryDropdown')">Category ▼</div>
        <div class="filter-dropdown-content" id="categoryDropdown"></div>
      </th>
      <th>
        <div class="filter-dropdown" onclick="toggleDropdown('subcategoryDropdown')">Subcategory ▼</div>
        <div class="filter-dropdown-content" id="subcategoryDropdown"></div>
      </th>
      <th>
        <div class="filter-dropdown" onclick="toggleDropdown('productDropdown')">Product ▼</div>
        <div class="filter-dropdown-content" id="productDropdown"></div>
      </th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

<script>
var data = [
    { Category: "Category 1", Subcategory: "Subcategory 1", Product: "Product 1"},
    { Category: "Category 1", Subcategory: "Subcategory 2", Product: "Product 2"},
    { Category: "Category 2", Subcategory: "Subcategory 3", Product: "Product 3"},
    { Category: "Category 2", Subcategory: "Subcategory 1", Product: "Product 4"},
    { Category: "Category 2", Subcategory: "Subcategory 3", Product: "Product 5"},
];

// JavaScript for filtering the table
function filterTable() {
  var table, tbody, tr, td, i, txtValue;
  var inputs = document.querySelectorAll('input[type="text"]');
  var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
  var filters = Array.from(inputs).map(input => input.value.toUpperCase());
  var filterValues = {
    category: [],
    subcategory: [],
    product: []
  };
  checkboxes.forEach(function(checkbox) {
    if (checkbox.classList.contains('categoryFilter')) {
      filterValues.category.push(checkbox.value.toUpperCase());
    } else if (checkbox.classList.contains('subcategoryFilter')) {
      filterValues.subcategory.push(checkbox.value.toUpperCase());
    } else if (checkbox.classList.contains('productFilter')) {
      filterValues.product.push(checkbox.value.toUpperCase());
    }
  });
  table = document.getElementById("myTable");
  tbody = table.getElementsByTagName("tbody")[0];
  tbody.innerHTML = ""; // Clear existing table body
  data.forEach(function(item) {
    if (
      (filters[0] === "" || item.Category.toUpperCase().includes(filters[0])) &&
      (filters[1] === "" || item.Subcategory.toUpperCase().includes(filters[1])) &&
      (filters[2] === "" || item.Product.toUpperCase().includes(filters[2])) &&
      (filterValues.category.length === 0 || filterValues.category.includes(item.Category.toUpperCase())) &&
      (filterValues.subcategory.length === 0 || filterValues.subcategory.includes(item.Subcategory.toUpperCase())) &&
      (filterValues.product.length === 0 || filterValues.product.includes(item.Product.toUpperCase()))
    ) {
      var row = document.createElement("tr");
      Object.values(item).forEach(function(value) {
        var cell = document.createElement("td");
        cell.appendChild(document.createTextNode(value));
        row.appendChild(cell);
      });
      tbody.appendChild(row);
    }
  });
}

// JavaScript for resetting filters
function resetFilters() {
  var inputs = document.querySelectorAll('input[type="text"]');
  inputs.forEach(input => input.value = "");
  var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
  checkboxes.forEach(checkbox => checkbox.checked = false);
  filterTable(); // Reset the table to its initial state
}

// JavaScript for dropdown filters
function toggleDropdown(dropdownId) {
    var dropdown = document.getElementById(dropdownId);
    dropdown.style.display = (dropdown.style.display === 'block') ? 'none' : 'block';
}

// Function to get unique values from an array
function getUniqueValues(data, key) {
  return Array.from(new Set(data.map(item => item[key])));
}

// Populate table on page load
window.onload = function() {
  filterTable();
};

// Populate dropdown options
function populateDropdown(dropdownId, options) {
  var dropdownContent = document.getElementById(dropdownId);
  dropdownContent.innerHTML = "";
  options.forEach(function(option) {
    var label = document.createElement("label");
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.value = option;
    checkbox.className = dropdownId === "categoryDropdown" ? "categoryFilter" :
                         dropdownId === "subcategoryDropdown" ? "subcategoryFilter" : "productFilter";
    checkbox.addEventListener("change", function() {
      filterTable();
      if (dropdownId === "categoryDropdown") {
        filterSubcategories();
        filterProducts();
      } else if (dropdownId === "subcategoryDropdown") {
        filterProducts();
      }
    });
    label.appendChild(checkbox);
    label.appendChild(document.createTextNode(option));
    dropdownContent.appendChild(label);
  });
}

// Populate dropdowns on page load
window.onload = function() {
  var categoryOptions = getUniqueValues(data, "Category").sort();
  var subcategoryOptions = getUniqueValues(data, "Subcategory").sort();
  var productOptions = getUniqueValues(data, "Product").sort();
  populateDropdown("categoryDropdown", categoryOptions);
  populateDropdown("subcategoryDropdown", subcategoryOptions);
  populateDropdown("productDropdown", productOptions);
  filterTable(); // Populate the table
};

// Filter subcategories based on selected categories
function filterSubcategories() {
  var categoryCheckboxes = document.querySelectorAll('.categoryFilter:checked');
  var subcategoryCheckboxes = document.querySelectorAll('.subcategoryFilter');
  subcategoryCheckboxes.forEach(function(checkbox) {
    // checkbox.disabled = true;
    checkbox.parentNode.style.display = "none";
  });
  categoryCheckboxes.forEach(function(checkbox) {
    var subcategoryOptions = data.filter(function(item) {
      return item.Category === checkbox.value;
    }).map(function(item) {
      return item.Subcategory;
    });
    subcategoryCheckboxes.forEach(function(subCheckbox) {
      if (subcategoryOptions.includes(subCheckbox.value)) {
        subCheckbox.parentNode.style.display = "block";
      } else {
        subCheckbox.parentNode.display = "none";
        subCheckbox.checked = false;
      }
    });
  });
}

// Filter products based on selected subcategories
function filterProducts() {
  var categoryCheckboxes = document.querySelectorAll('.categoryFilter:checked');
  var subcategoryCheckboxes = document.querySelectorAll('.subcategoryFilter:checked');
  var productCheckboxes = document.querySelectorAll('.productFilter');
  productCheckboxes.forEach(function(checkbox) {
    checkbox.parentNode.style.display = "none";
    // checkbox.display = false
  });
  subcategoryCheckboxes.forEach(function(checkbox) {
    var productOptions = data.filter(function(item) {
      return item.Subcategory === checkbox.value;
    }).map(function(item) {
      return item.Product;
    });
    productCheckboxes.forEach(function(prodCheckbox) {
      if (productOptions.includes(prodCheckbox.value)) {
        prodCheckbox.parentNode.style.display = "block";
      } else {
        prodCheckbox.parentNode.style.display = "none";
        prodCheckbox.checked = false;
      }
    });
  });
}
</script>

</body>
</html>

Changing permissions on video or audio stops all WebRTC MediaStreams

I’m doing a web application in React that resembles a web conference app, so I require camera and microphone access.

When I request access for the camera and microphone, I do it with a single prompt, as encouraged in the Media Capture and Streams W3C Draft. So I get access to both devices and everything works fine.

The problem I have is the following – I have these three objects:

let both = await navigator.mediaDevices.getUserMedia({video: true, audio: true});

// Separate streams
let video = await navigator.mediaDevices.getUserMedia({video: true, audio: false});
let audio = await navigator.mediaDevices.getUserMedia({audio: true});

They all have different MediaStream IDs, and different MediaStreamTrack‘s IDs. So they can’t be related or associated.

But, when I revoke the permissions to the video or audio (I’m using Google Chrome, so this should be up to date), the three MediaStreams get deactivated.

I’ve done a little bit of field research, and analysing the behaviour of say, Google Meet, this does not happen. When I revoke the permissions, the video stream or audio stream remain untouched.

Right now, what I’m doing is: if the permission is revoked, relaunch the getUserMedia function with only video or audio allowed. I want to understand why this happens, and if maybe the getUserMedia function uses some context that sets this behaviour.

I have read the Media Capture and Streams W3C Draft, and the WebRTC Overview, but I seem unable to find an answer.

How to make “Show More” button with Flask and Javascript?

I have one array of items and I want to display then in a unordered list. First I want to just show a few of these and after I press the button “Show More”, the others items get displayed on browser.

I’m trying to pass the array to the template and using the for loop of Flask , display the itens (but not all of them) to browser. And using javascript DOM functions, displays the rest os elements.
I dont know how to solve this or how to find the best way.

I tried to do it in some ways, but the best approach displayed just one item, not all of the others, the format of unordered list is vanished (The dots on the left os the text, i dont really know if this is a bug or an error).

This is one of the attempts:

The Flask app:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def home():
    lista = ['test-1', 'test-2', 'test-3', 'test-4', 'test-5', 'test-6', 'test-7']
    return render_template('home.html', lista=lista)

if __name__ == "__main__":
    app.run(debug=True)

And the HTML code is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Array Test</h1>
    <ul>
      {% for item in lista[:3] %}
        <li>{{ item }}</li>
      {% endfor %}

      {% for item in lista[3:] %}
        <li class="show" style="display: none;">
          {{ item }}
        </li>
      {% endfor %}
    </ul>
    <button class="buttonShow">Mostrar mais</button>

    <script>
      const buttonShow = document.getElementsByClassName("buttonShow")[0]
      const showItens = () => {
        document.getElementsByClassName("show")[0].style.display = "inline";
      }
      buttonShow.addEventListener('click', showItens)
    </script>
</body>
</html>

TailwindCSS to CSS3

I don’t know why react is easier than css3(cascading stylesheet) but
Is there any way to convert Tailwind CSS from react to normal CSS?
I tried to write it manually but takes lot of time but some of the property also not easy to understand.

want get result from this JavaScript code

I am having a problem with my form input not appearing under my table headings after submitting. Even after I have gone through the code a number of times. What can be the problem of my code?

Or do have any suggestions in writing the code correctly and easier?

When I enter the values and submit, the table still remains the same with no changes or alteration.

//MY JAVASCRIPT CODE
var form = document.getElementById("form");
var table = document.getElementById("table");
//add event listener to form 
form.addEventListener("submit", addItem);

function addItem(e) {
  e.preventDefault();

  // get customer name input value
  var AxNumber = document.getElementById("Ax-Number").value;

  //get item purchased input value
  var AxDate = document.getElementById("Ax-Date").value;

  //get quantity input value
  var AxReciveDate = document.getElementById("Ax-Recive-Date").value;

  // get date input value
  var Beneficiary = document.getElementById("Beneficiary").value;

  var Descrption = document.getElementById("Descrption").value;

  var Amount = document.getElementById("Amount").value;

  var Currency = document.getElementById("Currency").value;

  var Branch = document.getElementById("branch").value;

  //create rows
  var row = table.insertRow(2);
  //create row cells
  var customerCell = row.insertCell(0);
  customerCell.innerHTML = AxNumber;

  var ItemCell = row.insertCell(1);
  ItemCell.innerHTML = AxDate;

  var quantityCell = row.insertCell(2);
  quantityCell.innerHTML = AxReciveDate;

  var dateCell = row.insertCell(3);
  dateCell.innerHTML = Beneficiary;

  var dateCell = row.insertCell(4);
  dateCell.innerHTML = Descrption;

  var dateCell = row.insertCell(5);
  dateCell.innerHTML = Amount;

  var dateCell = row.insertCell(6);
  dateCell.innerHTML = Currency;

  var dateCell = row.insertCell(7);
  dateCell.innerHTML = Branch;

  var DeleteCell = row.insertCell(8);
  DeleteCell.innerHTML = "<button>x</button>";

}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link href="style.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>

<body>

  <form id="form">
    <div class="row">
      <div class="col">
        <input type="number" class="form-control" id="AxNumber" placeholder="Ax-Number">
        <input type="date" class="form-control" id="Ax-Date" placeholder="Ax-Date">
        <input type="date" class="form-control" id="Ax-Recive-Date" placeholder="Ax-Recive-Date">
        <input type="text" class="form-control" id="Beneficiary" placeholder="Beneficiary">
        <input type="text" class="form-control" id="Descrption" placeholder="Descrption">
        <input type="number" class="form-control" id="Amount" placeholder="Amount">
        <select id="Currency" class="form-select" aria-label="Default select example">
          <option selected>Selct Currency</option>
          <option value="1">EGP</option>
          <option value="2">USD</option>
          <option value="3">GPB</option>
        </select>
        <select id="branch" class="form-select" aria-label="Default select example">
          <option selected>Selct Branch</option>
          <option value="1">Kantara</option>
          <option value="2">Arish</option>
          <option value="3">Cairo</option>
          <option value="3">Cairo..</option>
        </select>
        <button type="submit" class="btn btn-primary">Submit</button>
      </div>

    </div>

  </form>

  <br />

  <table class="table table-hover" id="table">
    <thead class="border border-primary">
      <tr class="border border-primary">

        <th class="border border-primary" scope="col">Ax-Number</th>
        <th class="border border-primary" scope="col">Ax-System-Date</th>
        <th class="border border-primary" scope="col">Ax-Recive-Date</th>
        <th class="border border-primary" scope="col">Beneficiary</th>
        <th class="border border-primary" scope="col">Descrption</th>
        <th class="border border-primary" scope="col">Amount</th>
        <th class="border border-primary" scope="col">Currency</th>
        <th class="border border-primary" scope="col">Branch</th>
      </tr>
    </thead>
    <tbody>
      <tr class="border border-primary">

        <td class="border border-primary">54125</td>
        <td class="border border-primary">8-Nov-2023</td>
        <td class="border border-primary">8-Nov-2023</td>
        <td class="border border-primary">hhh</td>
        <td class="border border-primary">662033</td>
        <td class="border border-primary">544111</td>
        <td class="border border-primary">USD</td>
        <td class="border border-primary">united</td>
      </tr>

    </tbody>
  </table>

</body>

</html>

When choosing an option in the select I have to disable the non-matching selects

I need to disable mismatched selects based on the option of a fixed select.

In particular I have the select ‘Flatlist’; in each option of this select I pass a ‘data-option’ attribute which corresponds to the ‘data-select’ attribute of the selects with names “cars”, “pets”, “languages”.

The code below works almost fine. I’m having a small problem!

When I try to select a second option from the ‘Flatlist’ select again, all three selects are disabled, while I want it to have the same behavior as if I clicked on this select the first time.

document.getElementById('flatlist').addEventListener('change', function () {
    let attribute_select = event.target.options[event.target.selectedIndex].getAttribute("data-option");

    document.querySelectorAll('.selects').forEach(sel => {
        if (sel.getAttribute('data-select') !== attribute_select) {
            sel.value = "";
            sel.disabled = true;
        }
    })
});
<label for="flatlist">Flatlist:</label>
    <select name="flatlist" id="flatlist">
        <option value="">--Please choose an option--</option>
        <option data-option="car" value="choosecars">I choose the select cars</option>
        <option data-option="pet" value="choosepets">I choose the select pets</option>
        <option data-option="language" value="chooselanguages">I choose the select languages</option>
    </select>

    <label for="cars">Choose a car:</label>
    <select data-select="car" name="cars" id="cars" class="selects" onchange="changeSelect()">
        <option value="">--Please choose an option--</option>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>

    <label for="pet-select">Choose a pet:</label>
    <select data-select="pet" name="pets" id="pet-select" class="selects" onchange="changeSelect()">
        <option value="">--Please choose an option--</option>
        <option value="dog">Dog</option>
        <option value="cat">Cat</option>
        <option value="hamster">Hamster</option>
        <option value="parrot">Parrot</option>
        <option value="spider">Spider</option>
        <option value="goldfish">Goldfish</option>
    </select>

    <label for="lang">Language</label>
    <select data-select="language" name="languages" id="lang" class="selects" onchange="changeSelect()">
        <option value="">--Please choose an option--</option>
        <option value="javascript">JavaScript</option>
        <option value="php">PHP</option>
        <option value="java">Java</option>
        <option value="golang">Golang</option>
        <option value="python">Python</option>
        <option value="c#">C#</option>
        <option value="C++">C++</option>
        <option value="erlang">Erlang</option>
    </select>

I hope I have been clear enough in explaining the problem. However the above code is working, easy to understand this problem!

Thanks to those who will help me!