Skip to content
Advertisement

Javascript and HTML defer tag not working

The Javascript function below works perfectly when at the bottom of html file. However, I need it in main.js file. It has been suggested that adding the defer tag to the script tag will enable this but unfortunately not. It prints the first console.log but then stops. Any suggestions?

<script src="/static/main.js" defer></script>
// function to add items to shopping
let cartbutton = document.getElementsByName('ropebutton');
console.log(cartbutton) // prints node []
const cart = [];
    
for(var i = 0; i < cartbutton.length; i++) {
    let button = cartbutton[i];
    console.log(button); // doesn't print
    button.addEventListener('click', (event) => {
        console.clear();
        console.log(event.target);
        console.log(event.target.dataset.test);
        cart.push(event.target.dataset.test);
        console.log(cart)            
    });
};
<div class="column">
        <img src="static/111.jpg" alt="Rope" class="imgsize">
        <button class="btn btn-dark" data-test="rope111" id="rope111" name="ropebutton" onclick="addcart(this.value);" type="submit">$4,500 buy</button>
        <img src="static/112.jpg" alt="Rope" class="imgsize">
        <button class="btn btn-dark" data-test="rope112" id="rope112" name="ropebutton" type="submit">$3,500 buy</button>
        <img src="static/113.jpg" alt="Rope" class="imgsize">
        <button class="btn btn-dark" data-test="rope113" id="rope113" name="ropebutton" type="button">$1,550 buy</button>
    </div>```

Advertisement

Answer

There are two methods to have your code executed after loading the HTML content and to avoid blocking the render of the page. Either reference your script at the end of your <body> tag or in <head> but with defer attribute.

You can try referencing the script at the end of your <body> tag like this:

<bod>
    <div class="column">
        <img src="static/111.jpg" alt="Rope" class="imgsize">
        <button class="btn btn-dark" data-test="rope111" id="rope111" name="ropebutton" onclick="addcart(this.value);" type="submit">$4,500 buy</button>
        <img src="static/112.jpg" alt="Rope" class="imgsize">
        <button class="btn btn-dark" data-test="rope112" id="rope112" name="ropebutton" type="submit">$3,500 buy</button>
        <img src="static/113.jpg" alt="Rope" class="imgsize">
        <button class="btn btn-dark" data-test="rope113" id="rope113" name="ropebutton" type="button">$1,550 buy</button>
    </div>

    <script src="/static/main.js"></script>
</body>

I can’t see any issues in your JS code that prevent you from using either methods

8 People found this is helpful
Advertisement