Reputation: 2157
I've been trying everything and reading everywhere and can't seem to get this to work. What the heck am I doing wrong...
var visibility = $('#short-link').css('visibility');
$('#share-link span').click(function() {
if (visibility != 'hidden'){
$('#short-link').css({visibility: 'visible'});
} else {
$('#short-link').css({visibility: 'hidden'})
}
});
Please help
Upvotes: 0
Views: 1006
Reputation: 253318
I'd suggest:
$('#share-link span').click(function() {
this.style.visibility = this.style.visibility == 'visible' ? 'hidden' : 'visible';
});
This avoids using jQuery methods to update the inline style of the node, and avoids setting a needless variable (which then has to be updated as the visibility changes).
This seems way better from what your saying, I haven't messed around with pure JS yet, just jQuery. So instead of "this", wouldn't I use #short-link? Do I make it a javascript object?
If you'd rather stay with a more jQuery approach then I'd suggest:
$('#share-link span').click(function() {
$(this).css('visibility', function(i,v){
return v == 'visible' ? 'hidden' : 'visible';
});
});
Assuming, of course, that it's the span
you wish to act on.
Upvotes: 1
Reputation: 2967
I guess you are missing quotes on visiblity
$('#short-link').css('visibility','visible');
or
$('#short-link').css({'visibility':'visible'});
Upvotes: 0
Reputation: 298176
You're checking the visibility outside of the event handler, so it won't really change by itself.
In addition to Dave's answer, if you just want to toggle the visibility of the element, .toggle
might work:
$('#share-link span').click(function() {
$('#short-link').toggle();
});
The difference between your approach and this one is that .toggle()
toggles between display: none
and your original display
value instead of changing the visibility
property.
Upvotes: 0
Reputation: 46259
I imagine this isn't behaving as you expect because you're defining visibility outside your function, so it never changes. I think you intended to write:
$('#share-link span').click(function() {
var visibility = $('#short-link').css('visibility');
if (visibility != 'hidden'){
$('#short-link').css({visibility: 'visible'});
} else {
$('#short-link').css({visibility: 'hidden'})
}
});
or better, cache the object but not the property:
var $shortLink = $('#short-link');
$('#share-link span').click(function() {
var visibility = $shortLink.css('visibility');
if (visibility != 'hidden'){
$shortLink.css({visibility: 'visible'});
} else {
$shortLink.css({visibility: 'hidden'})
}
});
Upvotes: 2