Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing text color onclick

Tags:

javascript

I'm new to JavaScript. I've developed a page using JavaScript in such a way that when I select a color it is applied to the whole page as a background.

I want to develop a page where I can change only the text color. It should get changed (from red to green or something like that), but the page shouldn't get refreshed, and only the selected contents or text color should be changed.

Can any one please help me in this. Any ideas of how to develop it? Thanks in advance.

like image 957
Patel Avatar asked Jan 19 '10 05:01

Patel


2 Answers

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

like image 57
Erik Avatar answered Sep 28 '22 17:09

Erik


function func()
            {
                document.getElementById('text').style.fontSize='50px';
                document.getElementById('text').style.color='blue';
            }
<p id="text" onclick="func()">Font and color will be changed</p>
<button type="button" onclick="func()">Click here!</button>
like image 39
Anurag Giri Avatar answered Sep 28 '22 16:09

Anurag Giri