somdow
somdow

Reputation: 6318

Javascript if/else onclick help

I have a simple animation in CSS3 called "tap" and "untap".

I call it in via " className", and I'm trying to combine it so that onclick it does "tap" and onmouseout to "untap".

I have the click part working, but after the else statement it "doesn't work". What am I doing wrong?


<img src="picHere.gif" id="img7" onclick="if(this.className != 'tap') { this.className='tap'}  else {"onmouseout='this.className='untap'}; "/>

Upvotes: 0

Views: 2826

Answers (3)

FishBasketGordo
FishBasketGordo

Reputation: 23132

That's just invalid markup. Change it to something like this:

<script type="text/javascript">
    function onclickHandler(sender) {
        if (sender.className != 'tap') { 
            sender.className = 'tap';
        }
        return false;
    }
    function onmouseoutHandler(sender) {
        if (sender.className == 'tap') {
            sender.className = 'untap';
        }
        return true;
    }
</script>
<img src="picHere.gif" 
     id="img7" 
     onclick="return onclickHandler(this);" 
     onmouseout="return onmouseoutHandler(this);" />

Upvotes: 0

Jeremy Roman
Jeremy Roman

Reputation: 16345

You can't interleave the event handlers like that. Try this:

<img src="picHere.gif" id="img7" onclick="this.className='tap';" onmouseout='this.className='untap';" />

If you're willing to use jQuery, you could do something like this, which is cleaner yet:

<img src="picHere.gif" id="img7" />

// in your JavaScript code
$('#img7').click(function() { $(this).addClass('tap'); })
          .mouseout(function() { $(this).removeClass('tap'); });

Upvotes: 0

Joe
Joe

Reputation: 82584

You just need this:

<img src="picHere.gif" id="img7" 
    onclick="if(this.getAttribute('class') !== 'tap') this.setAttribute('class','tap');" 
    onmouseout="if(this.getAttribute('class') === 'tap') this.setAttribute('class','untap');" />

You could actually keep className, if you wanted. But the important thing to note here is that the onclick and onmouseout events are seperate.

Upvotes: 2

Related Questions