Why does a simple click function not find the selector? - javascript

I am writing a really quick js module that opens up and image and fades out a container to show the image. The markup for the image is this below:
<div style="margin-bottom:1px;" class="rsNavItem rsThumb front">
<div class="rsTmb portfolio">
<img src="http://www.mysterium.ch/revelation/pictures/revelation_highres_06.jpg"/>
</div>
</div>
Now what happens is the click basically fades out a div and then shows the container.
loadSlide: function () {
console.log('clicked');
//$('.rsThumb').each(function () {
var containerT = $('.rsnav-container'),
containerB = containerT.find('.rsThumb');
$('.rsThumb').click(function (e) {
console.log('clicked again');
e.preventDefault();
var sliderObject = $('.collection #gallery-t-group').data('royalSlider');
var s = this;
// Lets make sure the body is activated
$('body').addClass('rsSlider-active');
$('.loader').show().transition({
opacity: 1
}, 100, 'easeInOutQuart');
// $('.socialbar-vertical-static').removeClass('activestate');
$('.body').transition({
opacity: 0
}, 100, 'easeInOutQuart');
// After slider loads
setTimeout(function () {
$('.body').transition({
opacity: 1
}, 500, function() {
$('.loader').transition({
opacity: 0
}, 500).hide();
});
theSliderActivated();
theSocialActivated();
sliderObject.updateSliderSize(true);
$('div#container').css('margin',0);
}, 1000);
});
//});
}
The script is also loaded in at the top like so:
init: function() {
var app = this;
this.fakingIt();
this.loadSlide();
this.unloadSlide();
this.mobileNav();
this.loadThumbs();
this.royalSlider();
this.thumbsSwitch();
this.functionResize();
this.theSocialActivated();
this.slideEventChange();
console.log('======> new.global.js');
}
For some reason it will not register the event at all and even with a console log after the click nothing registers at all.
Am I doing something really wrong here?

Make sure you are definitely calling init() from within a document ready event handler. This will ensure the rsThumb div is available when binding to its click event.
$(function(){
init();
});

Related

AJAX load() not executing more than once

Transferred a website to server and now my JS file seems half-broken. When pictures are clicked AJAX is supposed to load a new page into the post box. However, I can't figure out why it only executes once and then stops working. Check it out.
http://affinity-cap.com/services/
and the JS file:
(function($) {
$("#wealthpic").click(function(){
$("#main").load("http://affinity-cap.com/wealth-management/ .post-box");
})
$("#portpic").click(function(){
$("#main").load("http://affinity-cap.com/portfolio-management/ .post-box");
})
$("#retirepic").click(function(){
$("#main").load("http://affinity-cap.com/retirement-consulting/ .post-box");
})
$(".service-pic").click(function(){
$(".post-box").animate({
opacity: 0.1
}, 1500);
})
}(jQuery));
Would appreciate help. Thanks.
#main contains the images you are clicking on. When you reload #main, it's going to cause issues with the handlers you set on the images. You should move those images to a separate div.
Try the following, it should replace your click events when "main" is reloaded:
(function($) {
$("#main").on("click", "#wealthpic", function(){
$("#main").load("http://affinity-cap.com/wealth-management/ .post-box");
})
$("#main").on("click", "#portpic", function(){
$("#main").load("http://affinity-cap.com/portfolio-management/ .post-box");
})
$("#main").on("click","#retirepic", function(){
$("#main").load("http://affinity-cap.com/retirement-consulting/ .post-box");
})
$(".service-pic").click(function(){
$(".post-box").animate({
opacity: 0.1
}, 1500);
})
}(jQuery));
make your html:
<div id="wealthpic" tail="wealth-management"></div>
<div id="portpic" tail="portfolio-management"></div>
<div id="retirepic" tail="retirement-consulting"></div>
and jquery:
(function($) {
/*define variables for repeatable use, if needed elsewhere*/
var url = 'http://affinity-cap.com/',
main = $('#main'),
wealthPic = $('#wealthpic'),
portPic = $('#portpic'),
retirePic = $('#retirepic'),
postBoxTxt = ' .post-box',
postBox = $(postBox),
animationSpeed = 1500;
/*main action*/
wealthPic.add(portPic).add(retirePic).click(function() {
//get html element tail attribute
var clickedElementTail = $(this).attr('tail');
//fade postBox out
postBox.stop().fadeTo(animationSpeed/2, 0.1, function() {
//change postBox content
main.load(url+clickedElementTail+postBoxTxt, function() {
//fade postBox in
postBox.fadeTo(animationSpeed/2, 1);
});
});
});
}(jQuery));
and let me know ;)

Jquery thumbnail gallery changing all images

I've tried to create a jQuery effect using fancy box to contain my content and within that is a large image with thumbnails below. What I was trying to make happen was when the thumbnails are clicked then the large image updates (see RACE Twelve image as an example). This works fine but the problem is when I go to another fancy box on my website (SEE RACE ONE box) then that image has been updated to be whatever thumbnail was clicked last.
I thought this might be event bubbling but preventing default hasn't helped.
I'm very new to jQuery and know that this is something stupid that I'm doing.
Any advice would be greatly appreciated? Thank you :)
Live version of page: http://www.goodwood.co.uk/members-meeting/the-races.aspx
jsfiddle for jQuery: http://jsfiddle.net/greenhulk01/JXqzL/
(function ($) {
$(document).ready(function () {
$('.races-thumbnail').live("click", function (e) {
$('.races-main-image').hide();
$('.races-image-wrap').css('background-image', "url('http://www.goodwood.co.uk/siteelements/images/structural/loaders/ajax-loader.gif')");
var i = $('<img />').attr('src', this.href).load(function () {
$('.races-main-image').attr('src', i.attr('src'));
$('.races-image-wrap').css('background-image', 'none');
$('.races-main-image').fadeIn();
});
return false;
e.preventDefault();
});
$(".races-image-wrap img").toggle(function () { //fired the first time
$(".races-pop-info").show();
$(this).animate({
width: "259px",
height: "349px"
});
}, function () { // fired the second time
$(".races-pop-info").hide();
$('.races-main-image').animate({
width: "720px",
height: "970px"
});
});
$('#fancybox-overlay, #fancybox-close').live("click", function () {
$(".races-pop-info").show();
$(".races-main-image").animate({
width: "259px",
height: "349px"
});
});
});
})(jQuery);
$('.races-main-image') will select all elements with that class, even the ones which aren't currently visible.
You can select the closest '.races-main-image' to the clicked element as per the code below (when placed inside the click event handler)
$('.races-main-image', $(e.target).closest('.races-fancy-box'))
So your new code should look like:
$('.races-thumbnail').live("click", function (e) {
var racesmainimage = $('.races-main-image', $(e.target).closest('.races-fancy-box'));
var racesimagewrap = $('.races-image-wrap', $(e.target).closest('.races-fancy-box'));
racesmainimage.hide();
racesimagewrap.css('background-image', "url('http://www.goodwood.co.uk/siteelements/images/structural/loaders/ajax-loader.gif')");
var i = $('<img />').attr('src', this.href).load(function () {
racesmainimage.attr('src', i.attr('src'));
racesimagewrap.css('background-image', 'none');
racesmainimage.fadeIn();
});
return false;
});
I've also removed your 'e.preventDefault();' return false; includes that, and was preventing e.preventDefault() from being executed in any case.

some issues with mouseenter and mouseleave functions

I have this function:
$(".insidediv").hide();
$(".floater").mouseenter(function(){
$(".hideimg").fadeOut(function(){
$(".insidediv").fadeIn();
});
});
$(".floater").mouseleave(function(){
$(".insidediv").fadeOut(function(){
$(".hideimg").fadeIn();
});
});
the function built to make a little animation, when you 'mouseenter' the div the picture I have there is hidden and than a few text show up.
it works fine if i move the mouse slowly. but if i move my mouse fast over the div the function getting confused or something and it shows me both '.insidediv and .hideimg,
how can i fixed that little problem so it wont show me both? thanks!
You need to reset the opacity, because fadeIn and fadeOut uses this css property for animation. Just stopping the animation is not enough.
This should work:
var inside = $(".insidediv"),
img = $(".hideimg");
duration = 500;
inside.hide();
$(".floater").mouseenter(function () {
if (inside.is(":visible"))
inside.stop().animate({ opacity: 1 }, duration);
img.stop().fadeOut(duration, function () {
inside.fadeIn(duration);
});
});
$(".floater").mouseleave(function () {
if (img.is(":visible"))
img.stop().animate({ opacity: 1 }, duration);
inside.stop().fadeOut(duration, function () {
img.fadeIn(duration);
});
});
I just introduced the duration variable to get animations of equal length.
Here is a working fiddle: http://jsfiddle.net/eau7M/1/ (modification from previous comment on other post)
try this:
var $insideDiv = $(".insidediv");
var $hideImg = $(".hideimg");
$insideDiv.hide();
$(".floater").mouseenter(function(){
$hideImg.finish().fadeOut(function(){
$insideDiv.fadeIn();
});
}).mouseleave(function(){
$insideDiv.finish().fadeOut(function(){
$hideImg.fadeIn();
});
});
This will solve your issue:
var inside = $(".insidediv"),
img = $(".hideimg");
inside.hide();
$(".floater").hover(function () {
img.stop(true).fadeOut('fast',function () {
inside.stop(true).fadeIn('fast');
});
},function () {
inside.stop(true).fadeOut('fast',function () {
img.stop(true).fadeIn('fast');
});
});
Updated Fiddle
You need to set the 'mouseleave' function when the mouse is still inside the
'floater' div.
Try this (i have tried it on the jsfiddle you setup and it works):
.....
<div class="floater">Float</div>
<div class="insidediv">inside</div>
<div class="hideimg">img</div>
var inside = $('.insidediv'),
img = $('.hideimg');
inside.hide();
$('.floater').mouseenter( function() {
img.stop().hide();
inside.show( function() {
$('.floater').mouseleave( function() {
inside.hide();
img.fadeIn();
inside.stop(); // inside doesn't show when you hover the div many times fast
});
});
});
.....

Auto hide element by jquery - code not work

I have an element in aspx page with class= "._aHide" it carrying a message, And it is shown repeatedly.
<div id="Message1" class="._aHide" runat="server" visible="true"><p>My Message</p></div>
aspx server side elements not created when page load if it's visible property = true.
I need to hide this div after 7 seconds of show it, unless mouse over.
I created this code
$(document).ready(function () {
var hide = false;
$("._aHide").hover(function () {
clearTimeout(hide);
});
$("._aHide").mouseout(function () {
hide = setTimeout(function () { $("._aHide").fadeOut("slow") }, 7000);
hide;
});
$("._aHide").ready(function () {
hide = setTimeout(function () { $("._aHide").fadeOut("slow") }, 7000);
hide;
});
});
But somthings wrong here
1- this code work for one time only, And I show this message many times.
2- All message boxes hides in one time, because I can't use $(this) in settimeout and I don't know why.
Thank you for your help, and I really appreciate it
Remove the point in the HTML code:
<div id="Message1" class="_aHide" runat="server" visible="true"><p>My Message</p></div>
See: http://api.jquery.com/class-selector/
tbraun89 is right, remove the "." in your html code.
Then, you can simplify your code like this :
JQuery hover have 2 functions using mouseenter and mouseleave
$(document).ready(function () {
var hide = false;
$("._aHide").hover(
function () {
//Cancel fadeout
clearTimeout(hide);
},
function(){
//re-set up fadeout
clearTimeout(hide);
hide = setTimeout(function () { $("._aHide").fadeOut("slow") }, 7000);
});
//Set up fadeout
hide = setTimeout(function () { $("._aHide").fadeOut("slow") }, 7000);
});

How can I hold Twitter Bootstrap Popover open until my mouse moves into it?

I have a link that uses the Twitter Bootstrap Popover version 1.3.0 to show some information. This information includes a link, but every-time I move my mouse from the link to the popover, the popover just disappears.
How can I hold popover open long enough to enable the mouse to move into it? Then when the mouse moves out of the link and popover, hide it?
Or is there some other plugin that can do this?
With bootstrap (tested with version 2) I figured out the following code:
$("a[rel=popover]")
.popover({
offset: 10,
trigger: 'manual',
animate: false,
html: true,
placement: 'left',
template: '<div class="popover" onmouseover="$(this).mouseleave(function() {$(this).hide(); });"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
}).click(function(e) {
e.preventDefault() ;
}).mouseenter(function(e) {
$(this).popover('show');
});
The main point is to override template with mouseleave() enabler. I hope this helps.
Bootstrap 3 and above
Simple, just use the container option and have it as the element that is calling the popover. This way, the popover is a child of the element that calls it. Hence, you are technically still hovering over the parent, because the child popover belongs to it.
For example:
HTML:
<div class="pop" data-content="Testing 12345">This has a popover</div>
<div class="pop" data-content="Testing 12345">This has a popover</div>
<div class="pop" data-content="Testing 12345">This has a popover</div>
jQuery:
Running an $.each() loop over every one of my elements that I want a popover binded to its parent. In this case, each element has the class of pop.
$('.pop').each(function () {
var $elem = $(this);
$elem.popover({
placement: 'top',
trigger: 'hover',
html: true,
container: $elem
});
});
CSS:
This part is optional, but recommended. It moves the popover down by 7 pixels for easier access.
.pop .popover {
margin-top:7px;
}
WORKING DEMO
Just to add to Marchello's example, if you want the popover to disappear if the user moves their mouse away from the popover and source link, try this out.
var timeoutObj;
$('.nav_item a').popover({
offset: 10,
trigger: 'manual',
html: true,
placement: 'right',
template: '<div class="popover" onmouseover="clearTimeout(timeoutObj);$(this).mouseleave(function() {$(this).hide();});"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
}).mouseenter(function(e) {
$(this).popover('show');
}).mouseleave(function(e) {
var ref = $(this);
timeoutObj = setTimeout(function(){
ref.popover('hide');
}, 50);
});
This is a little hacky, but building off of marchello's example, I did this (no need for template):
$(".trigger-link").popover({
trigger: "manual",
}).on("click", function(e) {
e.preventDefault();
}).on("mouseenter", function() {
var _this = this;
$(this).popover("show");
$(this).siblings(".popover").on("mouseleave", function() {
$(_this).popover('hide');
});
}).on("mouseleave", function() {
var _this = this;
setTimeout(function() {
if (!$(".popover:hover").length) {
$(_this).popover("hide")
}
}, 100);
});
The setTimeout helps ensure that there's time to travel from the trigger link to the popover.
This issue on the bootstrap github repo deals with this problem. fat pointed out the experimental "in top/bottom/left/right" placement. It works, pretty well, but you have to make sure the popover trigger is not positioned statically with css. Otherwise the popover won't appear where you want it to.
HTML:
<span class="myClass" data-content="lorem ipsum content" data-original-title="pop-title">Hover me to show a popover.</span>
CSS:
/*CSS */
.myClass{ position: relative;}
JS:
$(function(){
$('.myClass').popover({placement: 'in top'});
});
Solution worked for us for Bootstrap 3.
var timeoutObj;
$('.list-group a').popover({
offset: 10,
trigger: 'manual',
html: true,
placement: 'right',
template: '<div class="popover" onmouseover="$(this).mouseleave(function() {$(this).hide();});"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
}).mouseenter(function(e) {
$(this).popover('show');
}).mouseleave(function(e) {
var _this = this;
setTimeout(function() {
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
}, 100);
});
Here's my take: http://jsfiddle.net/WojtekKruszewski/Zf3m7/22/
Sometimes while moving mouse from popover trigger to actual popover content diagonally, you hover over elements below. I wanted to handle such situations – as long as you reach popover content before the timeout fires, you're save (the popover won't disappear). It requires delay option.
This hack basically overrides Popover leave function, but calls the original (which starts timer to hide the popover). Then it attaches a one-off listener to mouseenter popover content element's.
If mouse enters the popover, the timer is cleared. Then it turns it listens to mouseleave on popover and if it's triggered, it calls the original leave function so that it could start hide timer.
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
var container, timeout;
originalLeave.call(this, obj);
if(obj.currentTarget) {
container = $(obj.currentTarget).siblings('.popover')
timeout = self.timeout;
container.one('mouseenter', function(){
//We entered the actual popover – call off the dogs
clearTimeout(timeout);
//Let's monitor popover content instead
container.one('mouseleave', function(){
$.fn.popover.Constructor.prototype.leave.call(self, self);
});
})
}
};
Finally I fix this problem. Popover disappear is because Popover not child node of link, it is child node of body.
So fix it is easy, change bootstrap-twipsy.js content:
change .prependTo(document.body) to .prependTo(this.$element)
and fix position problem cause by change.
and some use link tiger popover will cause popover with link too, so add a span contain link, so problem solved.
This is a version of Wojtek Kruszewski solution. This version handle popover blink when mouse go back to trigger. http://jsfiddle.net/danielgatis/QtcpD/
(function($) {
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj) {
var self = (obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type));
originalLeave.call(this, obj);
if (obj.currentTarget) {
var current = $(obj.currentTarget);
var container = current.siblings(".popover");
container.on("mouseenter", function() {
clearTimeout(self.timeout);
});
container.on("mouseleave", function() {
originalLeave.call(self, self);
});
}
};
var originalEnter = $.fn.popover.Constructor.prototype.enter;
$.fn.popover.Constructor.prototype.enter = function(obj) {
var self = (obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type));
clearTimeout(self.timeout);
if (!$(obj.currentTarget).siblings(".popover:visible").length) {
originalEnter.call(this, obj);
}
};
})(jQuery);
I tried the solutions from #Wotjek Kruszewski and #danielgatis, but neither worked for me. Caveat: I'm using Bootstrap v2.1.0, not v3. This solution is in coffeescript (why are people still using plain javascript? =)).
(($) ->
originalLeave = $.fn.popover.Constructor::leave
$.fn.popover.Constructor::leave = (e) ->
self = $(e.currentTarget)[#type](#_options).data(#type)
originalLeave.call #, e
if e.currentTarget
container = $(".popover")
container.one "mouseenter", ->
clearTimeout self.timeout
container.one "mouseleave", ->
originalLeave.call self, e
) jQuery
Here is what i did:
e = $("a[rel=popover]")
e.popover({
content: d,
html:true,
trigger:'hover',
delay: {hide: 500},
placement: 'bottom',
container: e,
})
This is a very simple and awesone solution to this probelm, which i found out by looking into the bootstrap tooltip code. In Bootstrap v3.0.3 here is the line of code i noticed:
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this says that if container property of popover is defined then the popover gets appendTo() the element instead of insertAfter() the original element, all you need to do is just pass the element as container property. Because of appendTo() the popover becomes part of the link on which the hover event was binded and thus keeps the popover open when mouse moves on it.
This works for me on BootStrap 3:
el.popover({
delay: {hide: 100}
}).on("shown.bs.popover", function(){
el.data("bs.popover").tip().off("mouseleave").on("mouseleave", function(){
setTimeout(function(){
el.popover("hide");
}, 100);
});
}).on("hide.bs.popover", function(ev){
if(el.data("bs.popover").tip().is(":hover"))
ev.preventDefault();
});
At the end of the conversation linked by #stevendaniels is a link to a Twitter Bootstrap extension called BootstrapX - clickover by Lee Carmichael. This changes the popover from an overlarge tooltip into an interactive control, which can be closed by clicking elsewhere on the form, a close button, or after a timeout. Its easy to use, and worked very well for the project I needed it in. Some examples of its usage can be found here.
I didn't like any of the answers I've found, so I combined some answers that were close to make the following code. It allows you to end up just typing $(selector).pinnablepopover(options); every time you want to make a 'pinnable' popover.
Code that makes things easy:
$.fn.popoverHoverShow = function ()
{
if(this.data('state') !== 'pinned')
{
if(!this.data('bs.popover').$tip || (this.data('bs.popover').$tip && this.data('bs.popover').$tip.is(':hidden')))
{
this.popover('show');
}
}
};
$.fn.popoverHoverHide = function ()
{
if (this.data('state') !== 'pinned')
{
var ref = this;
this.data('bs.popover').$tip.data('timeout', setTimeout(function(){ ref.popover('hide') }, 100))
.on('mouseenter', function(){ clearTimeout($(this).data('timeout')) })
.on('mouseleave', function(){ $(this).data('timeout', setTimeout(function(){ ref.popover('hide') }, 100)) });
this.on('mouseenter', function(){ clearTimeout($(this).data('timeout')) });
}
};
$.fn.popoverClickToggle = function ()
{
if (this.data('state') !== 'pinned')
{
this.data('state', 'pinned');
}
else
{
this.data('state', 'hover')
}
};
$.fn.pinnablepopover = function (options)
{
options.trigger = manual;
this.popover(options)
.on('mouseenter', function(){ $(this).popoverHoverShow() })
.on('mouseleave', function(){ $(this).popoverHoverHide() })
.on('click', function(){ $(this).popoverClickToggle() });
};
Example usage:
$('[data-toggle=popover]').pinnablepopover({html: true, container: 'body'});
After seeing all Answer I made this I think it will be helpful .You Can manage Everything which you need.
Many answer doesn't make show delay I use this. Its work very nice in my project
/******
/*************************************************************/
<div class='thumbnail' data-original-title='' style='width:50%'>
<div id='item_details' class='popper-content hide'>
<div>
<div style='height:10px'> </div>
<div class='title'>Bad blood </div>
<div class='catagory'>Music </div>
</div>
</div>
HELLO POPOVER
</div>"
/****************SCRIPT CODE ****************** PLEASE USE FROM HEAR ******/
$(".thumbnail").popover({
trigger: "manual" ,
html: true,
animation:true,
container: 'body',
placement: 'auto right',
content: function () {
return $(this).children('.popper-content').html();
}}) .on("mouseenter", function () {
var _this = this;
$('.thumbnail').each(function () {
$(this).popover('hide');
});
setTimeout(function(){
if ($(_this).is(':hover')) {
$(_this).popover("show");
}
},1000);
$(".popover").on("mouseleave", function () {
$('.thumbnail').each(function () {
$(this).popover('hide');
});
$(_this).popover('hide');
}); }).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(_this).popover("hide");
}
}, 100); });
Now I just switch to webuiPopover, it just works.

Categories

Resources