Pregunta

I have a javascript function that I want to run on page load on my Shopify website, it checks if the user's username is longer than 24 characters, and if so breaks it onto two lines:

function checkName () {

    var customerName = document.getElementById('customername');

    if (customerName.innerHTML.length >= 24) {
        var length = customerName.innerHTML.length;
        var middle = Math.floor(length / 2);
        var firstHalf = customerName.innerHTML.slice(0, middle);
        var secondHalf = customerName.innerHTML.slice(middle);
        customerName.innerHTML = firstHalf + '<br />' + secondHalf;
    }
}

checkName();

When I run this in the console, it works fine. But linking to it as a file on my site gives me:

TypeError: customerName is null

I'm thinking that it's because it takes a second for Shopify to get the username and populate the element I tried adding setTimeout in different places of the function - but it still resulted in null.

¿Fue útil?

Solución

I'm guessing you have that script in the <head> tag. Place it just before the end of <body>. Remember, browsers read from top to bottom, so if you try to select an element with the id of customername before the browser has found it, it will return null.

Alternatively, you could only call the function when the page has finished loading with:

document.addEventListener('DOMContentLoaded', checkName);

Which will only run checkName when all of your HTML has been parsed (including the element with the id of customername).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top