1

This works with the onclick attribute:

<button type="button" onclick="this.style.color='red';">Astringents</button>

This works in the onclick attribute but not if called from the head element:

<head>
    <script type="text/javascript">
    function red() {
        this.style.color='red';
    }
    </script>
</head>

<button type="button" onclick="red();">Astringents</button>

EDIT: I want to use one function to serve several buttons. For example:

<button type="button" onclick="red();">Astringents</button>
<button type="button" onclick="red();">Exfoliators</button>
<button type="button" onclick="red();">Moisturizers</button>
<button type="button" onclick="red();">Masques</button/>

1 Answer 1

4

In this scenario, this is not referencing the <button> element - and therefore cannot edit a property of the element.

Check out the quirksmode article on this topic http://www.quirksmode.org/js/this.html

Based on the example at the bottom of the article, the following should work.

<head>
<script type="text/javascript">

function red(obj) {
    obj.style.color='red';
}
</script>
</head>

<button type="button" onclick="red(this)">Astringents</button>
Sign up to request clarification or add additional context in comments.

Comments

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.