How do I target $this (from 'each' context) from inside 'click' function. I want to remove awkward .parents().find() code.
$('.layout.responsive').each(function () {
$('.area.optional', this).before('<a href="#" class="toggle_responsive" onClick="return false">Show details</p>').hide();
$('.toggle_responsive', this).click(function () {
$(this).parents('.layout.responsive').find('.area.optional').toggle();
});
});
Save it in a named (non-special) variable:
$('.layout.responsive').each(function () {
var area = $('.area.optional', this).before('<a href="#" class="toggle_responsive" onClick="return false">Show details</p>').hide();
$('.toggle_responsive', this).click(function () {
$(area).toggle();
});
});
You can simply store it in a variable:
$('.layout.responsive').each(function () {
var $elem = $('.area.optional', this).before('<a href="#" class="toggle_responsive">Show details</p>').hide();
$('.toggle_responsive', this).click(function(e) {
e.preventDefault();
$elem.toggle();
});
});
Also note the e.preventDefault();
call which does pretty much what your onclick="return false;"
did but in a much cleaner way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With