skip to Main Content
const button1 = document.getElementById('1');
const button2 = document.getElementById('2');

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

function myFunc() {

    const elem = document.createElement('h1');

    button1.onclick = () => {

        location.assign('2.html');
        elem.textContent = '1';
        
            if (location.pathname === '/2.html') {
                main.appendChild(elem);
            }
        }

    button2.onclick = () => {
        location.assign('2.html');
        elem.textContent = '2';
        
            if (location.pathname === '/2.html') {
                main.appendChild(elem);
            }
    }
}

myFunc();
<button id="1" style="width: 100px; height: 30px;">Click</button>
<button id="2" style="width: 100px; height: 30px;">Click</button>

<main id="main"></main>

I have two buttons inside the first html file, and a main div inside the second html file. When I press a button inside the first html file, I want to update the second, by appending the h1 elem with the adequate textContent. Both html files are connected to the same js file. I tried doing it with pathname conditional, but it’s not working.

3

Answers


  1. You can’t do what you’re expecting to do the way you’re doing it.

    Location.assign() will (by default) navigate to another(or not) page. All your script will stop running and any variables will be discarded, including your main. The feature is commonly used to register the address modification in the history log of the browser (like going from anchor #some to #other and enabling going back to #some hitting the back button).

    You should, as Rory McCrossan suggested, store the state (or instructions of what to do at another page) at some cross-page context (like a cookie, sessionStorage, localStorage, …). When the target page loads, then it should read the state/instructions and do what you’re expecting it to do.

    Login or Signup to reply.
  2. To achieve your goal, you’ll need a way to communicate between the two HTML files. Since HTML files are separate, once the user clicks a button, the page will reload, and the main element will be rendered again on the second page. The problem you’re facing is that the JavaScript runs as the page loads, and since the page is redirected, the code to append the h1 tag in the second HTML file runs too late.

    One approach to handle this is to use localStorage or sessionStorage to persist data between page reloads or navigation. This way, you can store the information (e.g., which button was clicked) in the first page, and then retrieve and use it on the second page.

    Here’s an updated version of your code that uses localStorage to transfer data between the two pages:
    HTML 1:

        <button id="1" style="width: 100px; height: 30px;">Click</button>
        <button id="2" style="width: 100px; height: 30px;">Click</button>

    HTML 2:

    <main id="main">my test</main>

    Js:

     // Select the buttons and main container
    const button1 = document.getElementById('1');
    const button2 = document.getElementById('2');
    const main = document.getElementById('main');
    
    // Function to handle button clicks and redirect
    function myFunc() {
        // On the first page (index.html), store which button was clicked
        button1.onclick = () => {
            localStorage.setItem('buttonClicked', '1'); // Store the click information
            location.assign('2.html'); // Redirect to the second page
        };
    
        button2.onclick = () => {
            localStorage.setItem('buttonClicked', '2'); // Store the click information
            location.assign('2.html'); // Redirect to the second page
        };
    
        // On the second page (2.html), check localStorage for button click info
        if (location.pathname === '/2.html') {
            const clickedButton = localStorage.getItem('buttonClicked');
    
            if (clickedButton) {
                const elem = document.createElement('h1');
                elem.textContent = clickedButton; // Set the text based on which button was clicked
                main.appendChild(elem); // Append the element to the main container
                localStorage.removeItem('buttonClicked'); // Clear the stored value after using it
            }
        }
    }
    
    myFunc();
    Login or Signup to reply.
  3. Your html files are located on the server. Your Javascript file is also located on your server. A visitor of your site will enter the web address of your site into the browser address bar and hits enter. At this point a request is being sent from the web-browser of said user towards your server. This request is asking for the web-page.

    Your server received this request, loads or generates the HTML in order to respond to the question and embeds inline Javascript as inner content of script tags or references Javascript file(s) via the src attribute of the script tag.

    So, the HTML is generated/loaded by the server while preparing the response to a request and Javascript will be executed inside your user’s browser. Your user’s browser cannot access your HTML files, because they are located at the server, not at the browsers of your users. This is why direct file modification. You could redirect to the second html via:

    window.location.href = 'your/url/here';
    

    but you cannot write into a remote file located at the server from a client browser. It’s technically impossible and it would also be unsafe to allow your users to override your files.

    So, instead of that it would make much more sense to use a form and send a request via it, passing a meaningful parameter that the server will understand and will append to the content of the HTML.

    I strongly suggest you should not let users modify your files, so instead of that, save your user’s inputs and meaningful actions either inside your client-side (localStorage or sessionStorage) or inside user sessions on the server-side or even a database. And while you generate your HTML, make sure that you take into account the user session and append whatever content you would like.

    It’s unclear what your server-side technology is, but you could have a form wrapped around your buttons and a hidden input with the value, which would be modified to the right value when a button is being clicked:

    <form action="/my-action" method="POST">
        <hidden name="myaction">
        <button id="1" style="width: 100px; height: 30px;">Click</button>
        <button id="2" style="width: 100px; height: 30px;">Click</button>
    </form>
    

    and an event for your buttons:

    window.addEventListener("load", function() {
        for (let button of document.querySelectorAll("#1, #2")) {
            button.addEventListener("click", function() {
                let context = this.parentNode;
                context.querySelector("input").value = this.id;
                context.submit();
            });
        }
    });
    

    Your server-side code should handle the form submit, pick up what the myaction parameter is and write it to a log (inside the user session, db, whatever) and load the appropriate HTML, where the log you have just updated should be dynamically loaded and displayed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search