JOIN DEVPPL

It looks like you are new here. If you want to get involved, click on Join below!



simple problem. need help


T

keyboard_arrow_up
0
keyboard_arrow_down


First Post Mark as Spam telisjok
Posts: 1 - Registered: 2012-12-08 09:46:28

hello im new in this forum, also new in javascript..

i have this code
<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<p id="demo" style="color:#000000;">
JavaScript can change the style of an HTML element.
</p>

<script>
function myFunction()
{
x=document.getElementById('demo') // Find the element
if (x.style.match("ff"))
{
x.style="color:#000000";
}
else
{
x.style="color:#ff0000"; // Change the style
}
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>

</body>
</html>



but somethings wrong and the color doesnt change... any suggestions please?




J

keyboard_arrow_up
0
keyboard_arrow_down


Reply #2 Mark as Spam joesimmons
Posts: 5 - Registered: 2013-09-06 14:02:57

I don't recommend jQuery for such a simple script. It's not good for learning JavaScript, either.


The problem I see, is that 'x.style' is an object, not a string, so you can't use .match() on it. You should use 'x.style.color'
The problem, then, is that 'x.style.color' usually will return an rgb or rgba value (black is rgb(0, 0, 0) for example).
So, now that you know that, you can check 'x.style.color' for an rgb value, like so:

function myFunction() {
var x = document.getElementById('demo'); // Find the element

if (x.style.color === 'rgb(255, 0, 0)') {
x.style.color = 'rgb(0, 0, 0)';
} else {
x.style.color = 'rgb(255, 0, 0)';
}
}






JOIN DEVPPL

It looks like you are new here. If you want to get involved, click on Join below!




MENU
Advertising