Tooltip does not appear when searching input

I find myself struggling with tooltips again. I added an input to perform searches, and when I perform any search and try to see the tooltip, I only see the container (with its background color, borders and so on) but without the content of the tooltip. I will leave the example so that you can understand what happens:

document.getElementById('searchInput').addEventListener('keyup', function() {
            const searchText = this.value.toLowerCase();
        
            document.querySelectorAll('.table-mercado tbody tr').forEach(row => {
                const nameCell    = row.querySelector('td:nth-child(2)');
                const priceCell  = row.querySelector('td:nth-child(3)');
        
                const name = nameCell ? nameCell.textContent.toLowerCase() : '';
                const price = priceCell ? priceCell.textContent.toLowerCase() : '';
                
                if (name.includes(searchText) || price.includes(searchText)){
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
    
            });
        });
.table-mercado {
        border-collapse: collapse;
        width: 100%;
        border-spacing: 0; 
        border: none; 
    }

    .table-mercado .th-mercado, .td-mercado, .tr-mercado {
        padding: 10px;
        text-align: center;
    }

    .td-mercado div, .td-mercado form {
        justify-content: center;
        margin: auto;
    }

    .td-mercado button {
        margin: 0 auto; 
        display: block; 
    }

    .tooltip-mercado .tooltiptext-mercado {
        display: block;
        visibility: hidden;
        opacity: 0;
        width: 250px; 
        background-color: black;
        color: #fff;
        text-align: left;
        padding: 15px;
        border-radius: 5px;
        position: absolute;
        left: 100%; 
        top: 50%;
        transform: translateY(-50%); 
        z-index: 9999; 
        opacity: 0;
        transition: opacity 0.3s, visibility 0.3s;
        margin-left: 10px;
        box-sizing: border-box;
        white-space: nowrap;
        border: 1px solid #ddd;
        
    }

    .tooltiptext-mercado table {
        border-collapse: collapse;
        width: 100%;
    }

    .tooltiptext-mercado form {
        width: 100%;
        margin-top: 10px;
    }

    .tooltip-mercado .tooltiptext-mercado::after {
        content: "";
        position: absolute;
        top: 50%;
        left: -10px;
        transform: translateY(-50%);
        border-width: 5px;
        border-style: solid;
        border-color: transparent black transparent transparent;
    }

    .block-img:hover .tooltiptext-mercado{
        visibility: visible !important;  
        opacity: 1 !important; 
    }
    
    .th-mercado {
        cursor: pointer;
        position: relative;
        color: black;
        padding-right: 20px;
        text-align: left;
    }

    .th-mercado::after {
        content: '';
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 12px;
        opacity: 0.8;
        color: white;
    }
  
    
<input type="text" id="searchInput">
<div class="table-container">
    <table class="table-mercado">
        <thead>
            <tr class="tr-mercado">
                <th class="th-mercado"></th>
                <th class="th-mercado" >Nombre</th>
                <th class="th-mercado" >Price</th>
            </tr>
        </thead>
        <tbody>
                <tr class="row-mercado">
                    <td class="td-mercado" style="width: 60px; height: 60px; text-align: center; position: relative;">
                        <div class="block-img">
                            <img src="https://img.freepik.com/free-vector/earth-globe-icon-white-background_1308-125016.jpg" style="width: 60px; height: 60px; display: block;">   
                            <!-- Tooltip -->
                            <div class="tooltip-mercado">
                                <span class="tooltiptext-mercado">
                                    <table>
                                        <tr class="trtooltipmercado">
                                                <td>content</td>
                                        </tr>
                                    </table>
                                </span>
                            </div>
                        </div>
                    </td>
                    <td class="td-mercado"> Name1 </td>
                    <td class="td-mercado"> 10 </td>
                </tr>
                <tr class="row-mercado">
                    <td class="td-mercado" style="width: 60px; height: 60px; text-align: center; position: relative;">
                        <div class="block-img">
                            <img src="https://img.freepik.com/free-vector/earth-globe-icon-white-background_1308-125016.jpg" style="width: 60px; height: 60px; display: block;">   
                            <!-- Tooltip -->
                            <div class="tooltip-mercado">
                                <span class="tooltiptext-mercado">
                                    <table>
                                        <tr class="trtooltipmercado">
                                                <td>content</td>
                                        </tr>
                                    </table>
                                </span>
                            </div>
                        </div>
                    </td>
                    <td class="td-mercado"> Name2 </td>
                    <td class="td-mercado"> 50 </td>
                </tr>                                
        </tbody>
    </table>
</div>

Can I Style The DOM As This JavaScript Code Executes?

I am trying to print a specific column element from a web page and not print anything else that is displayed on the web page. The column element is centered on the web page and takes up 50% of the width of the web page. I have been able to do this using the following JavaScript code:

function printPageArea(areaID){
    var printContent = document.getElementById(areaID).innerHTML;
    var originalContent = document.body.innerHTML;
    document.body.innerHTML = printContent;
    window.print();
    document.body.innerHTML = originalContent;
}

The problem I’m having is that the column content (contained as HTML in the printContent variable) is being printed at 100% of the width of paper. This makes the text very small. Changing the orientation of the printed page from portrait to landscape helps a little, but not what I want.

What I’d like to be able to do is add some code to the JavaScript code above so that I could style the margins and font size of the printContent content before it is captured. I have tried doing that using document.getElementById(areaID).style = ... but it only changes the style of the (areadID) element AFTER the print window is dismissed.

Is it even possible to do what I want? If so, how?

How to Properly Scale and Use SVG Icons in WordPress Sidebar

Question:

I’m trying to implement a set of social media buttons in my WordPress sidebar using SVG icons. I am using the theme Agama Blue (version 1.1.5). The specific issue I’m facing is scaling the Facebook and X (formerly Twitter) icons to 24×24 pixels. All the icons are set to 24×24 pixels but still look odd and out of proportion.

I have already uploaded my icons to the WordPress media library, and here are the generalized URLs for the icons:

enter image description here

  • Facebook Icon: https://example.com/path-to-your-icons/facebook.svg
  • X Icon: https://example.com/path-to-your-icons/x.svg

Additionally, I have provided a screenshot of the section of my WordPress page that shows my social links, which is causing the problem.

Here’s what I’m trying to achieve:

  1. Both the Facebook and X icons need to be adjusted proportionally since for X it is bigger than the text and for Facebook it is really small .
  2. The icons should not have borders.
  3. The text for Facebook, X, and YouTube needs to be white.
  4. On hover, I want the icons to slightly grow in size, along with the pill-shaped button.

Here is the HTML and CSS code I have so far:

<div class="social-buttons">
    <a href="mailto:[email protected]" class="social-link mail" target="_blank">
        <img src="https://example.com/path-to-your-icons/email.svg" alt="Email Icon" class="social-icon" /> Mail
    </a>
    <a href="https://www.facebook.com/example" class="social-link facebook" target="_blank">
        <img src="https://example.com/path-to-your-icons/facebook.svg" alt="Facebook Icon" class="social-icon facebook-icon" /> Facebook
    </a>
    <a href="https://x.com/example" class="social-link x" target="_blank">
        <img src="https://example.com/path-to-your-icons/x.svg" alt="X Icon" class="social-icon x-icon" /> X
    </a>
    <a href="https://youtube.com/example" class="social-link youtube" target="_blank">
        <img src="https://example.com/path-to-your-icons/youtube.svg" alt="YouTube Icon" class="social-icon" /> YouTube
    </a>
</div>

<style>
.social-buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 10px;
    width: 100%;
}

.social-link {
    display: flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: 25px;
    text-decoration: none;
    font-size: 16px;
    font-weight: bold;
    flex: 1 1 calc(50% - 10px);
    justify-content: center;
    color: white;
    border: none;
    transition: transform 0.3s ease-in-out;
}

.social-link:hover {
    transform: scale(1.1);
}

.social-icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
    display: inline-block;
    transition: transform 0.3s ease-in-out;
    border: none;
}

.social-link:hover .social-icon {
    transform: scale(1.2);
}

.mail {
    background-color: #e0e0e0;
    color: black;
}

.facebook {
    background-color: #4267B2;
    color: white;
}

.x {
    background-color: #000000;
    color: white;
}

.youtube {
    background-color: #FF0000;
    color: white;
}

.mail .social-icon {
    filter: brightness(0);
}

.facebook .social-icon,
.x .social-icon,
.youtube .social-icon {
    filter: brightness(0) invert(1);
}

@media (max-width: 768px) {
    .social-link {
        flex: 1 1 100%;
    }
}
</style>

Current Issues:

  1. The Facebook and X icons are not scaling properly.
  2. The text color for Facebook, X, and YouTube appears gray instead of white.
  3. The hover effect works, but the icons sometimes don’t resize proportionally.

What I’ve Tried:

  • Using filter: brightness(0) invert(1); to make the icons white.
  • Adjusting the icon dimensions directly in CSS.

What I Need:

  • Properly scale the SVG icons to 24×24 pixels without distortion.
  • Ensure the text color for Facebook, X, and YouTube is white.
  • Make the hover effect resize both the button and the icon proportionally.

How can I adjust my CSS/HTML or SVG properties to make the icons scale correctly and the text color render properly?

Thanks in advance for any help!


How to create a React hook to detect page refresh only once and return false on subsequent mounts?

I am trying to create a React hook that will detect if the user has just refreshed the page. The hook should return true only on the first interaction after the page refresh. On subsequent mounts or interactions, it should return false as long as the user does not refresh the page again.

I tried using the performance.getEntriesByType('navigation') method to detect if the page was reloaded and then clearing the performance entries using performance.clearResourceTimings(). However, this approach did not work as expected. The hook still returns true on subsequent mounts, which is not the desired behavior.

I need a workaround or a different approach to ensure that the hook returns true only once after a page refresh and false on all subsequent mounts until the next page refresh.

import {useEffect} from 'react';
import {Platform} from 'react-native';

type UseDetectPageRefreshProps = {
    wasPageRefreshed: boolean;
};

function useDetectPageRefresh(): UseDetectPageRefreshProps {
    if (Platform.OS !== 'web') {
        return {wasPageRefreshed: false};
    }
    const isRefreshed = performance
        .getEntriesByType('navigation')
        .map((nav) => (nav as PerformanceNavigationTiming).type)
        .includes('reload');

    console.log('Page refresh detected:', isRefreshed);

    useEffect(() => {
        const resetRefreshStatus = () => {
            console.log('Resetting refresh status');
            // TODO: Clear performance entries navigation type to avoid false positives on future checks
        };

        if (isRefreshed) {
            resetRefreshStatus();
        }
    }, [isRefreshed]);

    return {wasPageRefreshed: isRefreshed};
}

export default useDetectPageRefresh;

I am looking for a solution that ensures the hook returns true only once immediately after a page refresh and false on all subsequent mounts or interactions until the next page refresh. Any help or guidance on how to achieve this would be greatly appreciated. Thank you!

Modify code to use mp3 as source instead of getUserMedia: Uncaught TypeError: Failed to execute ‘connect’ on ‘AudioNode’: Overload resolution failed

Trying to modify this code to use mp3 as source instead of getUserMedia microphone, but I’m not too familiar with the Web Audio API so I’m missing something and getting Uncaught TypeError: Failed to execute 'connect' on 'AudioNode': Overload resolution failed.

AudioAnalyzer.prototype.initWithoutStream = function () {

    /// modify code to use mp3 as source instead of browser microphone                                                                                        
    var audio = new Audio();
    audio.src = '/try.mp3';
    audio.controls = true;
    audio.autoplay = true;
    document.body.appendChild(audio);
    ////                                                                                                                                                      

    const audioCtx = new (
        window.AudioContext ||
        window.webkitAudioContext ||
        window.mozAudioContext ||
        window.msAudioContext)();

                                                                                                                       
    this.gain = audioCtx.createGain();
    this.gain.gain.value = 70.;

    const lowPass = audioCtx.createBiquadFilter();
    lowPass.type = "lowpass";
    lowPass.frequency.value = 1000;

    const highPass = audioCtx.createBiquadFilter();
    highPass.type = "highpass";
    highPass.frequency.value = 20000;

    this.analyzer = audioCtx.createAnalyser();
    this.analyzer.fftSize = this.FFT_SIZE;

    // const mediaStreamSource = audioCtx.createMediaStreamSource(stream);                                                                                    
    var source = audioCtx.createMediaElementSource(audio);
    source.connect(this.analyser); // ERROR
    this.analyser.connect(audioCtx.destination);
    // ^^^ modified / added ^^^        

    // Node tree                                                                                                                                              
    // mediaStreamSource.connect(this.gain);                                                                                                                  
    source.connect(this.gain);
    this.gain.connect(lowPass);
    this.gain.connect(highPass);
    lowPass.connect(this.analyzer);
    highPass.connect(this.analyzer);

    this.reset();

    this.audioBuffer = new Uint8Array(this.analyzer.frequencyBinCount);

    this.isInit = true;
    this.isPulse = true;

};

Modal opens twice when winning condition is met in React quiz game

I’m building a React quiz app where a modal should appear once all answers are correct or when the user loses all the lives. However, the modal opens twice instead of once despite my attempts to control the state. I tried managing the modal display using a state variable showModal. I’ve also attempted adding a flag to control it but the issue persists. What could be causing this issue, and how can I fix it?

const handleModalClose = () => {
  setShowModal(false);
};

const Modal = ({ isOpen, onClose }) => {
  const modalRef = useRef();

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (modalRef.current && !modalRef.current.contains(event.target)) {
        onClose();
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [onClose]);

  if (!isOpen) return null;
  if (correctAnswersCount >= 9) {
    confetti({
      particleCount: 100,
      spread: 70,
      origin: { y: 0.6 },
    });
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" ref={modalRef}>
        {correctAnswersCount > 9 && (
          <h2>Congrats! You've found all the correct answers!</h2>
        )}
        <h3>
          <b>Score</b>
        </h3>

        <div className="answer-progress-container">
          <div className="answer-progress">
            <div
              className="answer-progress-bar"
              style={{ width: `${(correctAnswersCount / 10) * 100}%` }}
            >
              {correctAnswersCount}/10
            </div>
          </div>
          <p className="streak-p">Current Streak: {streakCounter}</p>
        </div>
      </div>
      <button className="modal-close" onClick={onClose}>
        x
      </button>

The part where i call the modal, hope it’s clearer now;

{showModal && (
        <Modal
          isOpen={showModal}
          onClose={handleModalClose}
        />
      )}

VS Code: new empty line after JS auto-complete accepted

Recently, I updated VS Code to the version 1.93.0-1725459079_amd64 (now 1.93.1-1726079302_amd64, but didn’t fix the problem). I think I skipped some versions, but since the update, VS Code automatically inserts an empty line below the line I am coding in after accepting an auto-complete suggestion. The problem does not only occure when pressing enter, but also when pressing tab or when I click on the suggestion. (when coding in JavaScript, so I think the suggestions come from IntelliSense).
Here is an demonstration video

I searched the web a bit and tried changing a few settings like setting editor.suggest.insertMode to “replace”, setting editor.acceptSuggestionOnEnter to false, setting editor.suggestSelection to first, editor.tabCompletion to off and setting editor.suggest.snippetsPreventQuickSuggestions to false. I also started VS Code without extensions using the command code --disable-extensions, but nothing seems to work. (some of it is advice from AI, so maybe it’s not really fitting)
Maybe there is a new setting I don’t know of?

I am happy to hear about every answer that could help 🙂

The for loop only works once and then stops with Node is detached from document

The for loop is not working. After it’s done with the first, it stops with this error appearing in the console: Error: Node is detached from document

This is the code:

        const articles = await page.$$('body > main > div.min-h-screen > div > div:nth-child(2) > div');
        console.log("Articles: ", articles);
        for (let i = 0; i < articles.length; i++) {
            await articles[i].click('a');
            await page.waitForNavigation();
            await page.waitForSelector('body > main > div > div > .content-titles > h1');

            const pageTitle = await page.waitForSelector('body > main > div > div > .content-titles > h1');
            const title = await pageTitle?.evaluate(el => el.textContent);
            console.log("title: ", title);     
            await page.goBack();
        }

And this is basically what the elements look like:

<div><a href="..."></a><div>

The text in ckeditor5 is not updated

Excuse me, my English is bad.

There is such a code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.ckeditor.com/ckeditor5/43.1.0/ckeditor5.css" />

<body>
    <div id="addtext">button</div>
    <div id="inform">
        <div class="editor">
            <p>Hello from CKEditor 5!</p>
        </div>
    </div>
</body>

<script type="importmap">
    {
        "imports": {
            "ckeditor5": "https://cdn.ckeditor.com/ckeditor5/43.1.0/ckeditor5.js",
            "ckeditor5/": "https://cdn.ckeditor.com/ckeditor5/43.1.0/"
        }
    }
</script>

<script type="module">

    import {
        ClassicEditor,
        Essentials,
        Bold,
        Italic,
        Font,
        Paragraph
    } from 'ckeditor5';


    // При загрузки страницы
    ClassicEditor
        .create(document.querySelector('.editor'), {
            plugins: [Essentials, Bold, Italic, Font, Paragraph],
            toolbar: [
                'undo', 'redo', '|', 'bold', 'italic',
            ]
        })
        .then( /* ... */)
        .catch( /* ... */);

    $("#addtext").on("click", function () {
        var a = $('.editor').html();
        alert (a);
    })

</script>

I change the text in the ckeditor5 form and click addtext, as a result, I get the old text in the alert anyway. How do I get a new text in the ckeditor5 form?

enter image description here

I need the text to change dynamically.

Why does a JavScript .submit() call trigger the forms onsubmit event?

I have this form:

<?php
    if (!empty($_POST)) {
        header('Content-Type: text/plain');
        print_r($_POST);
        exit;
    }
?>

<!DOCTYPE html>
<html>
<body>

    <script>            
            setTimeout(function ()
            {
                document.forms[0].submit();
            }, 2000);
    </script>

    <form action="modaldialog-form-submit.html" method="post" id="myForm" onsubmit="alert('Why am I not seeing this alert when the form is submitted by JavaScript?');" >
        <input type="text" name="myText" value="Some text..." /><br />
        <textarea name="myTextarea">A text area</textarea><br />
        
        <input type="radio" value="1" name="myRadio" checked />Radio1<br />
        <input type="radio" value="22" name="myRadio" />Radio2<br />
        <input type="radio" value="333" name="myRadio" />Radio3<br />
        
        <select name="mySelect">
            <option value="first">First</option>
            <option value="second">Second</option>
            <option value="third">Third</option>
        </select>
        <p />
        <input type="submit" />
    </form>
    
</body>
</html>

When you click the submit button the onsubmit event is fired and you see the alert. But when the document.forms[0].submit() method is called it does not fire the onsubmit event.

Why is that?

How to fix Error: Could not find com.eightbitlab:blurview:1.6.3?

I haven’t been able to find a fix for this error so far:

Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'spreadfoundation'.
> Could not resolve all files for configuration ':classpath'.
   > Could not find com.eightbitlab:blurview:1.6.3.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
       - https://jcenter.bintray.com/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
     Required by:
         project :
* Get more help at https://help.gradle.org

BUILD FAILED in 12s

    at makeError (C:UsersVictorDocumentsSpreadspread-foundationnode_modulesexecaindex.js:174:9)
    at C:UsersVictorDocumentsSpreadspread-foundationnode_modulesexecaindex.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (C:UsersVictorDocumentsSpreadspread-foundationnode_modules@react-native-communitycli-platform-androidbuildcommandsrunAndroidrunOnAllDevices.js:109:5)
    at async Command.handleAction (C:UsersVictorDocumentsSpreadspread-foundationnode_modules@react-native-communityclibuildindex.js:192:9)
info Run CLI with --verbose flag for more details.

my android/build.gradle:

buildscript {
    ext {
      buildToolsVersion = "30.0.3"
      minSdkVersion = 21
      compileSdkVersion = 34
      targetSdkVersion = 34
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        // Top-level build file where you can add configuration options common to all sub-projects/modules.

        buildscript {
            ext {
              buildToolsVersion = "30.0.3"
              minSdkVersion = 21
              compileSdkVersion = 34
              targetSdkVersion = 34
            }
            repositories {
                google()
                jcenter()
            }
            dependencies {
                classpath 'com.eightbitlab:blurview:1.6.3'
                classpath("com.android.tools.build:gradle:8.0.0")

                // NOTE: Do not place your application dependencies here; they belong
                // in the individual module build.gradle files
            }
        }

        allprojects {
            repositories {
                mavenLocal()
                maven {
                    // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                    url("$rootDir/../node_modules/react-native/android")
                }
                maven {
                    // Android JSC is installed from npm
                    url("$rootDir/../node_modules/jsc-android/dist")
                }

                google()
                jcenter()
                maven { url 'https://www.jitpack.io' }
            }
        }
        //implementation 'com.facebook.fresco:sthetho:2.0.0'
        //classpath("com.android.tools.build:gradle:8.0.0")


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        mavenCentral()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

(I saw about JCenter closing and some ways to fix it, i read this: https://blog.gradle.org/jcenter-shutdown,but it didn’t work).

I looked in old questions but none of them helped, some from 2021 and one from 2023.

I made this application in 2020/21 and updated the API level, but I need to update again and I’m having problems with this module. The first correction I made was to add namespace = “…” in several modules because it was a slightly old application

Example code from Youtube Iframe API is not firing?

I’m trying to recreate Example 1 in YouTube’s own documentation on the YouTube Iframe API but am embedding a playlist as opposed to the single video in their example. However, I am unable to get it to work after much effort.

In YouTube’s example the <iframe> is placed in the page’s html instead of adding an empty <div> element which the player API’s JavaScript code then replaces with an <iframe> element. FYI this example should make the border of the iframe orange when first loaded, and then change colours when played, paused etc.

The iframe code in my page is as follows:

<iframe style="border-radius:12px; border: solid 14px #37474F;" aria-expanded"true" width="100%" height="704" src="https://www.youtube.com/embed/videoseries?enablejsapi=1&si=5tts7pEFZvX3undq&list=PL-Ov8WpjfHfnS90hc8DYyRCfllJkSFtHU&origin=https://www.futureproofpromotions.com/submit-to-futureproof-picks/" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

And the script I’ve added to the header is:

var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player_2', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady(event) {
  document.getElementById('player_2').style.borderColor = '#FF6D00';
}

function changeBorderColor(playerStatus) {
  var color;
  if (playerStatus == -1) {
    color = "#37474F"; // unstarted = gray
  } else if (playerStatus == 0) {
    color = "#FFFF00"; // ended = yellow
  } else if (playerStatus == 1) {
    color = "#33691E"; // playing = green
  } else if (playerStatus == 2) {
    color = "#DD2C00"; // paused = red
  } else if (playerStatus == 3) {
    color = "#AA00FF"; // buffering = purple
  } else if (playerStatus == 5) {
    color = "#FF6DOO"; // video cued = orange
  }
  if (color) {
    document.getElementById('player_2').style.borderColor = color;
  }
}

function onPlayerStateChange(event) {
  changeBorderColor(event.data);
}

The script is copied directly from the YouTube Example 1 & all I’ve done is change YouTube’s YT.Player('existing-iframe-example' to YT.Player('player_2'so that it references the iframe on my page.

WordPress has added the ID player_2 so that is why there’s no ID included in my iframe code above.

I have tried adding the script to the footer instead but that didn’t work either?

One thing I’m not sure about is: in the example script there is the line tag.id = 'iframe-demo'; and it doesn’t mention that parameter anywhere in its documentation so I’m not sure what to change it to, or whether I need to? I have tried removing the line (since it’s not included anywhere else in their documentation) and replacing iframe-demo with player_2 but still it doesn’t work.

You can view the page where I am trying to get this example to work here (the Youtube iframe is down the bottom in the middle).

Can anybody spot why the API / script is not firing and suggest a resolution?

Many thanks

How does Next.js decide between server and client execution, especially during routing?

I’ve been reading through Next.js documentation on rendering modes, including Server Components, Server Actions, and data fetching best practices. My understanding is that Next.js code can run in three contexts:

  1. Build time.
  2. Server side.
  3. Client side.

I’m confused about how Next.js decides whether code executes on the client or the server, especially during client-side routing (e.g., when clicking a link). Here’s what I understand so far:

Build Time Execution

Code is prevented from running at build time if:

  • export const dynamic = 'force-dynamic' is set.
  • "use client" is present at the top of the file.
  • Any of the functions cookies(), headers(), unstable_noStore(), unstable_after(), or searchParams are used (source).

Server-Side vs. Client-Side Execution

  • If the file starts with "use client", it runs client-side only.
  • Without "use client", the initial render runs server-side by default.

My Confusion: Preventing Client-Side Execution

Consider the following example from the official docs:

import { unstable_cache } from 'next/cache'
import { db, posts } from '@/lib/db'
 
const getPosts = unstable_cache(
  async () => {
    return await db.select().from(posts)
  },
  ['posts'],
  { revalidate: 3600, tags: ['posts'] }
)
 
export default async function Page() {
  const allPosts = await getPosts()
 
  return (
    <ul>
      {allPosts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

Clearly, getPosts() can only run server-side (it fetches from a database), but what happens when the page is rendered client-side during navigation?

  • Does Next.js always force server-side rendering when navigating between pages, even with client-side routing? How? Does it do something akin to RoR’s Hotwire?

  • Or, does it somehow translate the database call in some RPC style execution over network?

This part of Next.js isn’t very clear to me, and I’d appreciate any insight or clarifications on how Next.js handles this.

Firebase cloud function is returning Deadline exceeded on the console

Server:

exports.outerMainFunction = functions
  .runWith({
    timeoutSeconds: 540,
  })
  .https.onCall(
      async (request, context) => {
        return new Promise(async function (resolve) {
              try {
                let resp = await innerFunc()
                console.log("resp == ", JSON.stringify(resp))
                return resolve({
                  status: 'success'
                })  
              } catch (err) {
                  return resolve({
                  status: 'error'
                  })
              } 
        })
      }
)

module.exports.innerFunc = () => {
  return new Promise((resolve) => {

    let targetAudience = '' // url to the inner java cloud function
    const auth = new GoogleAuth()
    async function innerFunction() {
      const client = await auth.getIdTokenClient(targetAudience)
      const requestOptions = {
        url: targetAudience,
        method: 'POST',
        headers: {
          'Content-Type': '',
        },
        data: {},
        timeout: 300000,
      }
      console.log('Inside innerFunction: caling CF')
      const res = await client.request(requestOptions)
      return res
    }
    return innerFunction()
      .then(function (response) {
        let finalResp = JSON.parse(response.data)
        return resolve({ status: 'success in inner', result: finalResp })
      })
      .catch(function (error) {
        return resolve({ status: 'error in inner' })
      })
  })
}

Console:

const getFuncDetails = async () => {
  try {
    let data = {}
    let res = httpsCallable(getFunctions(), 'outerMainFunction')
    let result = await res(data)
    return result
  } catch (err) {
    console.log('Error while getting the details: ', JSON.stringify(err))
    return { status: 'error' }
  }
}

This is the code I have written. I am calling outerMainFunction from console side. The call is going through.
On the server end outerMainFunction is calling innerFunc. innerFunc is a java cloud function. If innerFunction is taking more than one minute to send the response, although on the server end I see proper logs with success status, on the console end getFuncDetails is going into catch block with the below error:
{“code”:”functions/deadline-exceeded”,”name”:”FirebaseError”}

I have given the below configurations for each function:
outerMainFunction – 512 mb with 540 sec timeout
innerFunction – 2gb with 540 sec timeout

Only when innerFunction is taking more than 1 minute to respond, I am facing this issue. How do I fix it?
I don’t see any issue with the timeout, not sure why it is not waiting.
I even tried logging some console logs and even reading/writing from firebase during the waiting time to not keep it idle but it’s not helping.
Also, since the error is seen on the console end, not sure what change needs to be done.
I even checked that default timeout might be 60 sec but when I go and list the cloud functions in cloud console, the above mentioned configurations are seen.
What else can be done to fix the issue?
Should I try converting the main function to express or change it to gen2? I am not sure if it’ll be helpful.
Any suggestion would be appreciated.