0

I try at the moment to re-color a clicked link from purple back to black.

It works if I add following code directly into the html file:

<script language="javascript">
window.onload = function() {
    document.getElementById("url").style.color = "#000000";
};

But I dont want to have that function in the HTML instead I put it into my .JS file. But it doesn't work.

    function changeColor() {
    document.getElementById("url").style.color = "#000000";
    }

and then call it like this in the body:

<script>
    changeColor(); //doesn't work
    $(document).ready( function () {
        changeColor(); //also doesn't work
    });
</script>

Any idea what is wrong?

1
  • Can you please include a complete code snippet - for something this simple you should be able to just include the whole thing in stack overflows code tool Commented Mar 19, 2018 at 17:22

3 Answers 3

1

Be sure that you are using the correct path of javascript file and if you want to use jQuery do not forget that you need the library.

Try this one :

window.init = changeColor();

function changeColor() {
  document.getElementById("url").style.color = "#000000";
}
<!-- <script src="js/nameOfYourFile.js" type="text/javascript"></script> -->

<a id="url" style="color:purple;" href="#">Hello</a>

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

Comments

1

The js file must not have <script>... </script> but pure code

   changeColor(); //doesn't work
   $(document).ready( function () {
    changeColor(); //also doesn't work
   });

and be sure you have a proper path in your html for include you js files .

eg :

<script src="./myscript.js"></script>

Comments

0

You can do this with jQuery:

$(document).ready(function() {
    $("#url").css("color: #000000");
});

make sure you included the file correctly.

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.