0

I want to get two html buttons of the class fontsizer. I need to create a variable, store the buttons in the variable, and then loop through the variable and assign each of the two buttons an event handler for onclick. In the end, when a button is clicked, it should run a method named resizeText.

Here is my JavaScript code:

function startup() {
    var fontButtons = document.getElementsByClassName("fontsizer");
    var i;
    alert(fontButtons.length);
    for (i = 0; i < fontButtons.length; i++) {
        fontButtons.elements[i].onclick = resizeText(this);
    }

    function resizeText(objButton) {
        var fontChange;
        fontChange = parseFloat(objButton.value);

        if (document.body.style.fontSize == "") {
            document.body.style.fontSize = "1.0em";
        }

        var currentFontSize;
        alert("changed");
        currentFontSize = parseFloat(document.body.style.fontSize);
        currentFontSize = currentFontSize+fontChange;
        document.body.style.fontSize = "currentFontSize+em"
    }

From my browser, the resizeText function is not run. When I check the size of fontButtons before looping, it is 0. Where am I going wrong?

1
  • fontButtons.elements[i] should be fontButtons[i] Commented Aug 8, 2014 at 16:21

1 Answer 1

3

The event handler for onclick is assigned to undefined. This is what the handler should look like

fontButtons[i].onclick=function(){resizeText(this);};

The reason is that this line of code has several issues

fontButtons.elements[i].onclick=resizeText(this);

First, fontButtons is already a NodeList containing the matched elements on the page, so using .elements will not contain any elements. Second, this is going to assign the onclick handler to the result of the resizeText function call. As the function does not return anything, the assignment gets undefined.

Using an anonymous function as the callback to call resizeText will allow for a new execution context to be created. The context created by the event handler will bind a new value to this allowing the current element that created the event to be sent to the resizeText function.

Sign up to request clarification or add additional context in comments.

2 Comments

Still no change.I think the line var fontButtons = document.getElementsByClassName("fontsizer"); doesnt retrieve the elements.Because the alert before the loop shows 0 as the lenght of fontButtons
@mungaihkamau - Make sure the script is executed after the elements are loaded into the DOM by either placing it at the very bottom of the page just before the closing body tag, or wrapping it in window.onload = function(){ startup(); };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.