Reputation: 18123
Here is a jsFiddle Demo of my problem
HTML
<div onclick="toggleFolder()" title="on" class="folderImage"><img src="..." id=" /></div>
javascript:
function toggleFolder() {
var toggle = $(this).attr('title');
if( toggle == 'on' )
{
$(this).addClass("folderImageActive");
$(this).attr('title','off');
}
else
{
$(this).removeClass("folderImageActive");
$(this).attr('title','on');
}
}
The problem is that when I click on the image, nothing happens. I was expecting it to add the class "folderImageActive" but it does not seem to do that.
Upvotes: 1
Views: 439
Reputation: 11381
I think you have to pass the element you're clicking to the function as an argument :
<div onclick="toggleFolder($(this))" title="on" class="folderImage"><img src="..." id=" /></div>
And your function :
<script>
function toggleFolder($this) {
//your code
}
</script>
Or, use .on()
. Give your div an id or class:
<div class="image-class" title="on" class="folderImage"><img src="..." id=" /></div>
Then, using jQuery's on
:
$(document).on("click", ".image-class", function () {
var isOn= this.title === 'on';
this.title= isOn ? 'off' : 'on';
$(this).toggleClass("folderImageActive", isOn);
});
Upvotes: 1
Reputation: 816780
Inside your function, this
refers to window
not to the element, because you are calling the function "normally": func()
. You have to set this
explicitly
onclick="toggleFolder.call(this)"
or better yet, bind the event handler with jQuery:
$('div.folderImage').click(toggleFolder);
You can also simplify your function to:
function toggleFolder() {
$(this).toggleClass('folderImageActive');
}
Resources:
this
in event handlersthis
Upvotes: 3
Reputation: 318302
Use jQuery for everything (almost) :
$('.folderImage').on('click', function() {
$(this).toggleClass('folderImageActive', this.title=='on');
this.title = this.title == 'on' ? 'off' : 'on';
});
Upvotes: 3