500man
500man

Reputation: 15

Javascript href attribute for css not updating

I am learning jquery and to test out my skills, I created a button that could switch styles with jquery, but that dosen't work for some reason. any ideas? Code:

<link id="original" rel="stylesheet" type="text/css" href="http://style.es.cx/style2.css">
<script>
function turnGrey(){
    document.getElementById("original").href="http://style.es.cx/style.css";<!-- what ever your new css file is called-->
}
</script>
<button id="grey" onclick="turnGrey">Turn Grey</button><br />
<pre>this text should change</pre>
<div>
    foobar
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

Upvotes: 0

Views: 162

Answers (4)

a45b
a45b

Reputation: 519

What are you doing? By the way this is one way to change css. or you can add or remove class also

$("#grey").removeClass("success").addClass("danger");

<link id="original" rel="stylesheet" type="text/css" href="http://style.es.cx/style2.css">
<script>
function turnGrey(){
    $("#grey").css('color', 'red');
    $("#grey").css('background-color', 'green');
}
</script>
<button id="grey" onclick="turnGrey()">Turn Grey</button><br />
<pre>this text should change</pre>
<div>
foobar
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

Upvotes: 0

Jai
Jai

Reputation: 74738

You have to call the function with ():

 onclick="turnGrey()"

and <!-- what ever your new css file is called--> this is not the way to have a comment in <script>.

Upvotes: 2

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

You have a lot of mistakes.

  1. You are using vanilla javascript, not jQuery (you include the library but the syntax used is not jQuery).

  2. Your function doesn't work since you are not calling it. You are writing onclick="turnGrey" when it needs to be onclick="turnGrey()".

  3. Change the stylesheet is not the good practice. It's better change the classname.

  4. The comments in javascript are like this: /* comment */. You are writing a comment in HTML inside a javascript code, that crashes completely your code.

However, here you are the code that could works (I remove jQuery library since you are not using don't eat machine resources):


<link id="original" rel="stylesheet" type="text/css" href="http://style.es.cx/style2.css">
<script>
function turnGrey(){
    document.getElementById("original").href="http://style.es.cx/style.css"; /* what ever your new css file is called */
}
</script>
<button id="grey" onclick="turnGrey()">Turn Grey</button><br />
<pre>this text should change</pre>
<div>
foobar
</div>

Upvotes: 1

senschen
senschen

Reputation: 804

The problem here is that turnGrey() is a function, but in your onclick you just have the function name. You aren't actually calling the function. Change onclick="turnGrey" to onclick="turnGrey()" and it should work.

Upvotes: 0

Related Questions