0

I'm very new to Javascript and this is my first time creating my own function. I'm trying to change the color of links based on whether or not the user clicks a button I've created. The code is as follows:

<p align="center">
    <input type="button";
           onclick="changelinks"
           value = "Click this if you can't see the links!"/>
</p>

This is the code I have for my function.

<script type="text/javascript">
              function changelinks(links) {
                var element = document.getElementByClass("links");
                element.onclick.color = "#00FF7F";
                 }
                 </script>

Do you have any suggestions to make my function work? How can I link my function to the button? Thanks in advance, I really appreciate it.

jjost26
  • 3
  • 2
  • possible duplicate of [Uncaught ReferenceError: function is not defined with onclick](http://stackoverflow.com/questions/17378199/uncaught-referenceerror-function-is-not-defined-with-onclick) – Maykonn May 09 '14 at 00:20

3 Answers3

1

Among others, these are some major issues:

1.There is no getElementByClass - there is getElementsByClassName or getElementById

2.element.onclick.color = "#00FF7F"; is wrong.

3.type="button"; onclick="changelinks" should not have a ; and changelinks needs ()

Try this:

<script type="text/javascript">
    function changelinks() {
        var element = document.getElementById("links");
            element.style.color = "#000";
    }
 </script>


<a href="#" id="links" style="color:#fff">Hello</a>

<p align="center">
    <input type="button" onclick="changelinks()" value = "Click this if you can't see the links!"/>
</p>

This is a simple example that will do what you one for one link id="links". To do something similar with multiple elements of the same class, see this question and the javascript manual.

Also, note that this example uses pure javascript, but a cleaner and simpler solution could be had using JQuery - see Johannes N's answer for details.

Community
  • 1
  • 1
Mark Miller
  • 7,442
  • 2
  • 16
  • 22
0

This can be easily done using jQuery.

Html:

<p id="button">Button</p>
<a href="" class="links">link</a>

JavaScript:

$(function() {
    $('#button').click(function() {
        $('.links').css("color", "red");
    });
});

Working example: http://jsfiddle.net/YS79d/

almo
  • 6,107
  • 6
  • 43
  • 86
0

addClass and removeClass in jquery does the trick

HTML/CSS

<style>
.links {
color:#FF0000;
}
.links2 {
color:#0000FF;
}
</style>
<p id="button">Button</p>
<a href="" class="links">link</a>

Javascript

$('#button').toggle(function () {
    $(".links").addClass("links2");
}, function () {
    $(".links").removeClass("links2");
});

Working JSFiddle example