dynamically loaded content does not load cart contents

Hello i have an app where i ma trying to sell some stuff.

basically there also exists a laravel app remotely which serves my HTML and CSS app

e.g

function fetchcart() {
    fetch('https://#################.com/cart')
        .then(response => response.text())
        .then(htmlContent => {
            const container = document.getElementById('cart');
            
            // Create a temporary div element
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = htmlContent;

            // Extract and append scripts to the container
            const scripts = tempDiv.getElementsByTagName('script');
            for (let i = 0; i < scripts.length; i++) {
                const script = document.createElement('script');
                script.innerHTML = scripts[i].innerHTML;
                container.appendChild(script);
            }

            // Append the rest of the HTML content
            container.innerHTML += tempDiv.innerHTML;
        })
        .catch(error => {
            console.error('Error fetching view:', error);
        });
}

// Fetch the HTML initially
fetchcart();

should load content directly into

   <div id="cart"></div>

in <div id="cart"></div>

we have products and a cart div

     <div id="transcart"></div>
     
<div class="col-md-11 p-0 mt-3">
    <div class="row row-cols-2 row-cols-md-3 row-cols-xl-4 g-2 g-md-3">
         @foreach($products as $d1)
        <div class="col mb-2">
          <div class="card h-100 p-2">
                     @if ($d1->file == '')
               
                        <img src="{{ URL::asset('uploads/not.png') }}" class="card-img-top min-height-lg min-height-sm rounded" alt="...">

@else

<img src="###############.com/images/{{$d1->file}}" class="card-img-top min-height-lg min-height-sm rounded" alt="...">

  @endif

           
            <div class="position-absolute top-0 end-0 bg-primary rounded text-white p-1 px-2 m-3" style="font-size:11px !important">₦{{ number_format($d1->price, 2) }}</div>
            <div class="card-body text-center text-md-start">
              <h5 class="card-title mb-0">{{$d1->title}}</h5>
             
            </div>
            <div class="card-footer border-0 bg-white">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <p style="display:none" class="mb-md-0 fs-6 mb-0 text-center text-md-start">
                            Price: <span class="text-primary">₦{{ number_format($d1->price, 2) }}</span>
                        </p>
                    </div>
                    <div class="col-md-6">
                      
                           @if($d1->product_quantity >= '1')
                                    <a  href="{{ route('addbook.to.cart', $d1->id) }}" class="btn btn-primary btn-sm white-text white-text-hover px-0 w-100 choice" role="button">Add to cart</a>
                                     @elseif($d1->product_quantity < '1')
                                      <a  href="#" class="btn btn-primary btn-sm white-text white-text-hover px-0 w-100" role="button">Out of stock</a>
                                      @endif
                    </div>
                </div>
            </div>
          </div>
        </div>
         @endforeach
    
    </div>
</div>

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
     </script>
     <script>

function wole() {
console.log('Before AJAX request');
$.ajax({
    url: "{!! url('/market') !!}",
    method: "get",
    dataType: "html",
    success: function (response) {
        console.log('AJAX success, response:', response);
        $("#transcart").html(response);
        // Other logic...
    },
    error: function (xhr, status, error) {
        console.error('AJAX error:', error);
    }
});
console.log('After AJAX request');

}


$(document).ready(function () {
  $(".choice").click(function (e) {
    e.preventDefault();
    $.ajax({
      url: $(this).attr("href"),
      method: "get",
      dataType: "html",
      success: function (response) {
       // $("#vote").html(response);
       alert('suce');
        wole();
      }
    });
  });
});
wole();

     </script>

this is the page that served dynamically into my app. which works.

infact when I add to cart I log the cart session created

[2023-12-05 04:49:40] production.INFO: New item added. Cart content: {"355":{"name":"testing product for Stephanie","quantity":1,"price":"2000","productid":355,"image":"chelsea.jpg"}}  

just to be sure that the session duly created.

but the my which should loa cart contents keeps showing empty.

what could be wrong?

this is the code that loads my cart contents

  @php $total = 0 

  @endphp




        @if(session('cart'))
            @foreach(session('cart') as $id => $details)
             @php $total += $details['price'] * $details['quantity'] @endphp
 
             <li style="margin-bottom : 10px" rowId="{{ $id }}">
                  <div class="row m-auto align-items-center">
                      <div class="col-md-4 col-3 px-0">
                             <div class="bg-cover rounded-2 small-list-image" style="background: url({{ URL::asset('public/uploads/'. $details['image']) }});">
                              
                             
                              
                          </div>
                      </div>
                      <div class="col-md-5  col-6">
                          <p class="mb-0">{{ $details['name'] }}</p>
                          <div class="input-group input-group-sm my-1">
                              <span class="input-group-text">Quantity</span>
                              <input readonly type="text" id="changer" value="{{ $details['quantity'] }}" class="form-control text-center changer" aria-label="quantity"><br />
                                
                            </div>
                             <div>
                                <a  href="{{ url('/changer/'.$id.'/'.'add') }}" class="changer"><i class="material-icons-outlined">add_circle_outline</i></a>
                          
                                  <a  href="{{ url('/changer/'.$id.'/'.'sub') }}" class="changer"><i class="material-icons-outlined">remove_circle_outline</i></a>
                                  
                                  </div>
                          <a class="btn btn-link p-0 m-0 text-decoration-none delete-product">Remove</a>
                      </div>
                      <div class="col-md-3 col-3">
                          <p class="text-primary">₦@php echo number_format($details['price'], 2) @endphp</p>
                      </div>
                  </div>
              </li>
              
   @endforeach
 
        @endif
  @if($total != '0')<br />
@php  $total @endphp



<script>
$('#move').unbind('click')
</script>

 @endif
   @if($total == '0')<br />
<h3><strong>Cart is empty</strong></h3>

i have also test my link https://#################.com/cart using an iframe its the same issue.

but when I test directly https://#################.com/cart on a browser everything is fine. i need this to work dynamically or using an iframe. preferable dynamically.

please help, my cart keeps returning empty

Advice on a stock simulation program

not really much of a problem but I’m looking for help/advice on a library that would make it fairly easy to make a real time simulation of the stock market

I only really know JavaScript, java, and python. If someone could help me that would be great!

Trouble with `fetch`: `catch` Block Not Executing for API Error Handling in JavaScript

I’m trying to fetch data from an API using fetch in my JavaScript code, and I want to handle errors properly. I’ve implemented the following code, but for some reason, the catch block is not executing even when there’s an error. Can anyone help me identify what might be causing this issue?

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log('Data received:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

I tried to fetch data from an API using the fetch function in JavaScript. I implemented error handling by checking the response status and throwing an error if it’s not okay. I expected that when an error occurs, the catch block would be executed to log the error message and after I expected the code to handle errors properly, logging an error message in the catch block when there is an issue with the API request, and otherwise, logging the received data in the appropriate then block. after trying for long, the catch block does not seem to execute as I wanted.

Axios is showing error while signing up on App

I am siging up for my mern stack app and it shows AXIOS error

following is the code for API Connector and auth respectively

It is an edtech project
when i fill the form of sign up then it shows error that
SENDOTP API error and error is AXIOS error

import axios from "axios"

export const axiosInstance = axios.create({});

export const apiConnector = (method, url, bodyData, headers, params) => {
    return axiosInstance({
        method:`${method}`,
        url:`${url}`,
        data: bodyData ? bodyData : null,
        headers: headers ? headers: null,
        params: params ? params : null,
    });
}
import { toast } from "react-hot-toast";
import { setLoading, setToken } from "../../slices/authSlice";
import { resetCart } from "../../slices/cartSlice";
import { setUser } from "../../slices/profileSlice";
import { apiConnector } from "../apiconnector";
import { endpoints } from "../apis";

const {
  SENDOTP_API,
  SIGNUP_API,
  LOGIN_API,
  RESETPASSTOKEN_API,
  RESETPASSWORD_API,
} = endpoints;

export function sendOtp(email, navigate) {
  return async (dispatch) => {
    const toastId = toast.loading("Loading...");
    dispatch(setLoading(true));
    try {
      const response = await apiConnector("POST", SENDOTP_API, {
        email,
        checkUserPresent: true,
      });
      console.log("SENDOTP API RESPONSE............", response);

      console.log(response.data.success);

      if (!response.data.success) {
        throw new Error(response.data.message);
      }

      toast.success("OTP Sent Successfully");
      navigate("/verify-email");
    } catch (error) {
      console.log("SENDOTP API ERROR............", error);
      toast.error("Could Not Send OTP");
    }
    dispatch(setLoading(false));
    toast.dismiss(toastId);
  };
}

export function signUp(
  accountType,
  firstName,
  lastName,
  email,
  password,
  confirmPassword,
  otp,
  navigate
) {
  return async (dispatch) => {
    const toastId = toast.loading("Loading...");
    dispatch(setLoading(true));
    try {
      const response = await apiConnector("POST", SIGNUP_API, {
        accountType,
        firstName,
        lastName,
        email,
        password,
        confirmPassword,
        otp,
      });

      console.log("SIGNUP API RESPONSE............", response);

      if (!response.data.success) {
        throw new Error(response.data.message);
      }
      toast.success("Signup Successful");
      navigate("/login");
    } catch (error) {
      console.log("SIGNUP API ERROR............", error);
      toast.error("Signup Failed");
      navigate("/signup");
    }
    dispatch(setLoading(false));
    toast.dismiss(toastId);
  };
}

export function login(email, password, navigate) {
  return async (dispatch) => {
    const toastId = toast.loading("Loading...");
    dispatch(setLoading(true));
    try {
      const response = await apiConnector("POST", LOGIN_API, {
        email,
        password,
      });

      console.log("LOGIN API RESPONSE............", response);

      if (!response.data.success) {
        throw new Error(response.data.message);
      }

      toast.success("Login Successful");
      dispatch(setToken(response.data.token));
      const userImage = response.data?.user?.image
        ? response.data.user.image
        : `https://api.dicebear.com/5.x/initials/svg?seed=${response.data.user.firstName} ${response.data.user.lastName}`;
      dispatch(setUser({ ...response.data.user, image: userImage }));

      localStorage.setItem("token", JSON.stringify(response.data.token));
      localStorage.setItem("user", JSON.stringify(response.data.user));
      navigate("/dashboard/my-profile");
    } catch (error) {
      console.log("LOGIN API ERROR............", error);
      toast.error("Login Failed");
    }
    dispatch(setLoading(false));
    toast.dismiss(toastId);
  };
}

export function logout(navigate) {
  return (dispatch) => {
    dispatch(setToken(null));
    dispatch(setUser(null));
    dispatch(resetCart());
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    toast.success("Logged Out");
    navigate("/");
  };
}

export function getPasswordResetToken(email, setEmailSent) {
  return async (dispatch) => {
    dispatch(setLoading(true));
    try {
      const response = await apiConnector("POST", RESETPASSTOKEN_API, {
        email,
      });

      console.log("RESET PASSWORD TOKEN RESPONSE....", response);

      if (!response.data.success) {
        throw new Error(response.data.message);
      }

      toast.success("Reset Email Sent");
      setEmailSent(true);
    } catch (error) {
      console.log("RESET PASSWORD TOKEN Error", error);
      toast.error("Failed to send email for resetting password");
    }
    dispatch(setLoading(false));
  };
}

export function resetPassword(password, confirmPassword, token) {
  return async (dispatch) => {
    dispatch(setLoading(true));
    try {
      const response = await apiConnector("POST", RESETPASSWORD_API, {
        password,
        confirmPassword,
        token,
      });

      console.log("RESET Password RESPONSE ... ", response);

      if (!response.data.success) {
        throw new Error(response.data.message);
      }

      toast.success("Password has been reset successfully");
    } catch (error) {
      console.log("RESET PASSWORD TOKEN Error", error);
      toast.error("Unable to reset password");
    }
    dispatch(setLoading(false));
  };
}

It has to be g for otp validation but it showing api error axios err

How to query the URL of the currently active tab in a background script

I have recently started writing a privacy extension that requires me to create a list of active domains to run a background task for each. I’m new to writing browser extensions, but my idea was to query the active tab using browser.tabs.query inside a chrome.tabs.onActivated event listener.

let activeTabDomain
const getActiveTabDomain = tabs => {
  activeTabDomain = tabs[0].url
}

const onError = _ => {
  activeTabDomain = "none"
}

chrome.tabs.onActivated.addListener(activeInfo => {
  browser.tabs.query({active: true, currentWindow: true}).then(getActiveTabDomain, onError)
  if (activeTabDomain) {
    const match = activeTabDomain.match(/^(?:https?://)?(?:www.)?([^/#]+)/)
    if (match) activeTabDomain = match[1]
    console.log(`domain: ${activeTabDomain}`)
  }                                                                                 
})  

However, when I run this code in a background script, the outcome I get is always the previous active domain being printed. Am I doing something wrong with the event listener?

IndexedDB MANIFEST grows to 15GB crashing the browser

I think I am running into this issue https://github.com/google/leveldb/issues/299

I use Dexie and my app run for many days. The data stored are not so large, and the number of entries are fixed, but an array field in each entry get appended every now and then. The MANIFEST file has grown to 15GB and I can no longer access my web site since it freezes and crashes the browser whenever it access IndexedDB.

How do I solve/workaround this issue?

Authenticate user updates using JWT

I want to let the user update their information by logging in and then update it through the JWT header, but I can’t. It keeps returning failed confirmation.

I want when the user logs in successfully, the information will be updated

my code

UserValidate

export default async function UserValidate(req, res, next) {
  try {
    // access authorize header to validate request
    const token = req.headers.authorization.split(" ")[1];

    // retrive the user details fo the logged in user
    const decodedToken = await jwt.verify(token, process.env.JWT_SECRET);

    req.user = decodedToken;

    next();
  } catch (error) {
    res.status(401).json({ error: "Authentication Failed!" });
  }
}

update user

export async function updateUser(req, res) {
  try {
    const { ID } = req.params;

    if (ID) {
      const {
        USERNAME,
        EMAIL,
        FIRST_NAME,
        LAST_NAME,
        DATE_OF_BIRTH,
        MOBILE,
        ADDRESS,
        AVATAR,
      } = req.body;

      const query = `
        UPDATE users 
        SET 
          USERNAME = ?, 
          EMAIL = ?, 
          FIRST_NAME = ?, 
          LAST_NAME = ?, 
          DATE_OF_BIRTH = ?, 
          MOBILE = ?, 
          ADDRESS = ?, 
          AVATAR = ? 
        WHERE ID = ?`;

      const values = [
        USERNAME,
        EMAIL,
        FIRST_NAME,
        LAST_NAME,
        DATE_OF_BIRTH,
        MOBILE,
        ADDRESS,
        AVATAR,
        ID,
      ];

      await connection.query(query, values, function (err) {
        if (err) {
          console.error("Error updating user:", err);
          return res.status(500).send({ error: "Internal Server Error" });
        }

        return res.status(201).send({ msg: "Record Updated...!" });
      });
    } else {
      return res.status(401).send({ error: "User Not Found...!" });
    }
  } catch (error) {
    console.error("Error updating user:", error);
    return res.status(500).send({ error: "Internal Server Error" });
  }
}

route update

router.route("/auth/update-user").put(userValidation, updateUser);

postman test

enter image description here

postman login

enter image description here

I tried putting Bearer in the Header section

enter image description here

how can in make that the icons are almost at the right edge of the “container” div but are aligned vertically

exampleHow can I make all the ( >i>
) are almost at the right edge of the “container” div but are aligned vertically

I want to achieve something similar to the image I attached as an example and as you will see you can see that all the arrows that point to the right are almost on the right side but are aligned vertically.

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>mi cuenta</title>
    <link rel="stylesheet" href="/css/micuenta.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css">
</head>
<body>
    <div id="contenedor">
        <h1 id="titulo">mi cuenta</h1>
        <div class="opciones" id="usuario">
            <button><img src="/img/seguridad.png" alt=""></button>
            <a href="">inicio de sesion y seguridad</a><i class="bi bi-chevron-right flecha "></i>
            <!--cambiar informacion personal del usuario-->
        </div>
        <div class="opciones" id="pedidos">
            <button><img src="/img/pedidos.png" alt=""></button>
            <a href="">mis pedidos</a><i class="bi bi-chevron-right flecha"  ></i>
            <!--todos procesando enviado entregado  cancelados por el usuario -->
        </div>
        <div class="opciones" id="paquetes">
            <button><i class="bi bi-geo-alt-fill"></i></button>
            <a href="">direccion</a><i class="bi bi-chevron-right flecha "></i>
            <!--direccion de entrega de paquetes-->
        </div>
        <div class="opciones" id="metodospago">
            <button> <i class="bi bi-credit-card"></i></button>
            <a href="">metodos de pago</a><i class="bi bi-chevron-right  flecha"></i>
            <!--tarjetas de credito del usuario-->
        </div>
        <div class="opciones" id="ayuda">
            <button><i class="bi bi-question-octagon"></i></button>
            <a href="">servicio al cliente</a><br><i class="bi bi-chevron-right  flecha"></i>
            <!--ayuda/ pqr-->
        </div>
    </div>
</body>
</html>

css

*{
    margin: 0;
    padding: 0;
    text-decoration: none;
    font-family: Arial, Helvetica, sans-serif;
    color: black;
    font-size: 24px;
}

body{}

#contenedor{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: absolute;
    top: 70%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 700px;
    height: 850px;
    background-color: wheat;
    border-radius: 30px;
    
}

img{
    width: 60px;
}

button{
    width: 90px;
    height: 90px;
    border-radius: 200px;
    border: none;
    cursor: pointer;
    display: inline-block;
}

.opciones{
    margin: 20px auto;
    width: 500px;
    display: flex;
    align-items: center;
}

i{
    font-size:32px;
}

#titulo{
    font-size: 40px;
    text-align: center;
    margin: 30px auto;
    
    
}

a{
    margin-left: 15px;
}


.flecha{
    color: black;
    font-size: 20px;
    display: inline-block;
}

To be honest, I haven’t been able to find a way to solve my problem.
filler textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller textfiller text

thank you for yor attention and have a nice night/day 🙂

How can a user who forget password reset the password

Users can sign in using either email/password or username/password. For username, the code creates a non-functioning email e.g [email protected]. email verification is set to false. A user may forget password so a help is provided using user questions/answers stored in firestore database collections. If the answers are correct, user can provide a new password which will be updated in firebase authentication. And this is my challenge, how to update user password in firebase authentication.

Below is my code:

import { getAuth } from "firebase/auth";
getAuth()
    .updateUser(userId, {
        email: enteredUsername.trim().toLowerCase(),
        emailVerified: false,
        password: enteredNewPassword.trim(),
        disabled: false,
    })
    .then((userRecord) => {
        console.log('Successfully updated user', userRecord.toJSON());
    })
    .catch((error) => {
        console.log('Error updating user:', error);
    });

Above gives error message:

TypeError: (0, _auth.getAuth)().updateUser is not a function (it is undefined), js engine: hermes
How do I correct this error

Now I have a config.js file (though I think this may not be useful for this purpose:

import { initializeApp } from "firebase/app";
import { getAuth} from "firebase/auth";//This is for dev
import { collection, initializeFirestore } from "firebase/firestore";//This is for production
import AsyncStorage from '@react-native-async-storage/async-storage';
import { initializeAuth, getReactNativePersistence } from "firebase/auth";

const firebaseConfig = {
  apiKey: "value",
  authDomain: "value",
  projectId: "value",
  storageBucket: "value",
  messagingSenderId: "value",
  appId: "value"
};

const app = initializeApp(firebaseConfig);
export const auth = initializeAuth(app, {
  persistence: getReactNativePersistence(AsyncStorage),
});
export const db = initializeFirestore(app, { experimentalForceLongPolling: true });// This is for production
export const userRef = collection(db, 'Users');

Make Div act as a device viewport

I’m currently working on a web based html editor and wanting to have a div wrapper act as a viewport for different screen sizes and devices. Is there a way to have media queries recognize a div as a viewport size? I know I can load an iframe into the div at 100% width and height and the display works as expected, but I was wanting it be just the div so that it would be easier to add rows, columns, etc.

Here is an example of how the div is setup now:

<div id="page-view" class="mobile">
   <div id="device-width" style="width: 430px; height: 932px;"></div>
</div>

I would like to be able to load in editable html inside the device-width div and it would respond like it would on a device at that size.

Django : Using Onclick To Div With Scrolling ( Tab Menu )

I’m trying to create tab menu with scroll. My actual problem is, How to scroll to section by clicking the button?

Smooth scroll to div id

Is there a better way to do this?

Thank you

my code :

html

<section id="section_{{ html_component.title }}" class="card">
    <div>
        <div>
            <h3>{{ html_component.title }}</h3>
        </div>
    </div>
</section>

<section id="section_{{ html_component.title }}" class="card">
    <div>
        <div>
            <h3>{{ html_component.title }}</h3>
        </div>
    </div>
</section>


<nav class="menu__main">
    <ul>
        {% for html_component in html_components %}
            <li>
                <a href="javascript:void(0);" onclick="ScrollTabMenu()">
                    <span>{{ html_component.title }}</span>
                </a>
            </li>
        {% endfor %}
    </ul>
</nav>


jquery


function ScrollTabMenu (){
    let TabMenu = $(`section_{{html_component.title}}`)
};

Please tell me the best solution for jQuery or Javascript?

Tailwind color classes not working in / elements in React

why cant I change the color for the mention elements without using inline styling? I would like to use only tailwind classes instead of inline.

index.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
    font-family: Inter, sans-serif;
    font-feature-settings: 'liga' 1, 'calt' 1;
}

@supports (font-variation-settings: normal) {
    :root { font-family: InterVariable, sans-serif; }
}

*{
    box-sizing: border-box;
}

body{
    background-color: #000;
    margin:0;
    padding: 24px 5% 8px 5%;
    min-height: 100%;
}

a{
    color: white;
}

NavBar component (jsx):

import { Link, NavLink } from 'react-router-dom'

export const NavCard = () => {
    return (
        <nav className='bg-custom-black flex items-center justify-between max-w-7xl mr-auto ml-auto py-4 px-8 rounded-full'>
            <Link to='/' className='no-underline text-xl font-semibold'>
                rogelio romo.
            </Link>
            <div className='text-xl font-semibold'>
                <NavLink style={{color: '#22C55E'}} className='no-underline px-6'> home. </NavLink>
                <NavLink style={{color: '#8a8a93'}} className='no-underline px-6'> projects. </NavLink>
                <NavLink style={{color: '#8a8a93'}} className='no-underline px-6'> contact. </NavLink>
            </div>
        </nav>
    )
}

If i don’t declare the anchor with its css rules in the index.css file, Preflight sets by default the inherit color of the parent.

Javascript POST not passing data [duplicate]

I have a javascript function to send variable data to a post request to a php file and everything seems to work on it but the $_POST data on the receiving file is showing the request as “null”. I have tried replacing the “1234” with the variable tmnum and the other way around and both don’t seem to be posting it to display.php.

function LoadTM(tmnum) {
        fetch("display.php", {
  method: "POST",
 body: JSON.stringify({ tm: "1234" }),
  headers: {
    "Content-type": "'Content-Type': 'application/json'"
  }
})
    .then((response) => response.text())
    .then((html) => {
        document.getElementById("detailpanel").innerHTML = html;
    })
    .catch((error) => {
        console.warn(error);
    });
    }   

In the display.php file I have:

<? echo $_POST['tm'] . " - Number";?> 

but is just echos – Number indicating no post info. No errors and I don’t have access to the console.

How to tell CSS my Web Component attribute has mutated

If you look at me simple example here you with see that test_button.html has some inline CSS: –

#myBtn[clicked="true"] {
    opacity: 0.5;
}

This seems to work as long as I go through the componet’s attribute setter for “clicked”. That is the AttributeChanged event is called and CSS reacts.

But as my clicked event occurs on the Shadow DOM there is no way I can see (bar using a closure to send the custom element’s “this” to the event handler) of accessing the accessor for “clicked”.

The user/caller of my Web Component could stick a data-clicked attribute on #myBtn and maintain it themselves in their own event handler but shouldn’t attribute-change be something that can bubble up from the shadow DOM to the light DOM?