I’m having trouble getting Twipsy to read the data attributes set on Twipsy-enabled element.
I have an <input...> control with the following attributes set:
rel="twipsy"
data-trigger="focus"
The <head...> element contains the following JS script:
$(document).ready(function () {
$(function () {
$('[rel=twipsy]').twipsy({ live: true });
});
});
When executed, Twipsy is triggered by the mouseenter and mouseleave events, not focus and blur, as the documentation suggests.
So I changed the JS script on my page to:
$(document).ready(function () {
$(function () {
$('[rel=twipsy]').twipsy({ live: true, trigger: ($(this).attr('data-trigger') == 'focus' ? 'focus' : 'hover') });
});
});
Same result. Although I’ve been using Prototype for a long time, I only started playing with JQuery about a week ago, so it’s entirely possible (OK – highly probable) that I simply don’t understand how JQuery handles collections, enumeration and this.
$(document).ready(function () {
$(function () {
$('[rel=twipsy]').each(function () {
var trigger = $(this).attr('data-trigger')
$(this).twipsy({ live: true, trigger: (trigger == 'focus' ? 'focus' : 'hover') })
});
});
});
And this works as expected.
So my question is this: What was I doing wrong in the first two examples? Why wasn’t the data-trigger attribute of the element being recognised and what was wrong with the JS script in the second example?
In the second case:
You’ve used
$(this)inside an anonymous function, it’s pointing at thedocumentobject. You fixed it by putting the “work” inside of a.each()where jQuery was kind enough to set the context ofthisto what you had expected, your target. jsFiddleYour final solution is pretty much optimised. You are asking for a different action to be taken for each element of the matched set depending on some logic relating to its properties, so you are going to have to iterate over all of them in some way.The only change I would make is:
self-executing anonymous function was redundant
going to use a ternary for a switch case, I’d do it when saving the
variable.