Why isnt my $().css({ "visibility": "visible"}) working? - javascript

I can't seem to get my jquery <div id="NotificationDotOnNav" > {{NotificationNavDot}} </div> function to work!
Find below the helper file:
<template name="home">
<div id="NotificationDotOnNav" > {{NotificationNavDot}} </div>
</template>
Find below my helper file:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0) {
$("#NotificationDotOnNav").css({ "visibility": "visible"});
alert("Testing!");
return;
}
else {
$("#NotificationDotOnNav").css({ "visibility": "hidden"});
}
},
});
When run, a popup with Testing! displays, clearly meaning the flow actually enters the if (numberOfNotifications > 0), however the $("#NotificationDotOnNav").css({ "visibility": "visible"}); fails to fire up!
What I find very strange is that, when copy & paste and run: $("#NotificationDotOnNav").css({ "visibility": "visible"}); in the browser console, it works!
Can someone kindly explain why it only fires-up when run in the browser console and not otherwise? Also kindly help me get this simple code to work.
I have included the relevant CSS file, in case this will help
#NotificationDotOnNav{
top: 10px;
float: right;
right: 5%;
visibility: hidden;
position: absolute;
z-index: 5;
min-width: 10px;
padding: 7px 7px;
border-radius: 20px;
background-color: #f54555ad;
}
Looking forward to your help!

Make sure your helper function execute after the Document Object Model (DOM) is ready and becomes safe to manipulate (this could be the reasons why your code runs when you type it in dev console but not when your run your js).
You can use $( document ).ready( handler ) (doc) for that.
Please consider a minimal reproducible example so we can help you out with more details.
By the way, you could also improve your code by caching the selector and using a ternary to write it more succinctly:
...
const numberOfNotifications = recipientsDetails.find({counts:1}).count();
const elm = $("#NotificationDotOnNav") // query the DOM just once
numberOfNotifications > 0 ? elm.show() : elm.hide()
...

Try it like this:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0) {
$("#NotificationDotOnNav").css('opacity', '1');
alert("Testing!");
return;
} else {
$("#NotificationDotOnNav").css('opacity', '0');
}
}
});
Also change your CSS code:
#NotificationDotOnNav {
top: 10px;
float: right;
right: 5%;
opacity: 0; /* this has been changed */
position: absolute;
z-index: 5;
min-width: 10px;
padding: 7px 7px;
border-radius: 20px;
background-color: #f54555ad;
}

I found a walk around the issue that works.
Find below the changes that I've made to enable the code to work.
Find below updates I've made to my HTML code:
<template name="home">
<span id="NotificationDotOnNav" class="badge animated"> {{NotificationNavDot}} </span>
</template>
Find below my helper file:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0 ) {
$("#NotificationDotOnNav").css({"visibility": "visible"});
return 0;
}
else {
$("#NotificationDotOnNav").css({ "visibility": "hidden"});
}
}
});
Find below my CSS:
#NotificationDotOnNav{
top: 11px;
float: right;
right: 10%;
height: 13px;
width: 1px;
position: fixed;
visibility: hidden;
z-index: 9;
font-size: xx-small;
color: #f5455500;
background-color: #f54555b5;
}
Nevertheless Id like to thank everyone for their contributions.

Related

Why animate's callback function (complete) executed at start?

Duplicate:
Yes it is but a little bit different from this.
I'm using jQuery 3.1.0 This is my code:
$(document).ready(function () {
ToggleAsideBar();
});
function ToggleAsideBar(){
$(".ah-sidebar-toggle").click(function(){
let toggleSize = $(".ah-logo").width() == 230 ? "50px" : "230px";
$(".ah-logo").animate(
{ width: toggleSize },200,"linear",function () {alert("Animation Complete!");'}
);
});
}
Problem:
In my case, alert show before the animation starts. I want to show alert after the animation completed. Any thoughts what I am doing wrong in above code?
Live Example:
jsfiddle
You had a collision between jquery's animation and css's transition.
If you decide to use animate - you should remove the transition lines from your css file.
Here is a working version (without the transition in your css):
$(document).ready(function () {
ToggleAsideBar();
});
function ToggleAsideBar(){
//Get width of browser
$(".ah-logo").click(function(){
let toggleSize = $(".ah-logo").width() == 230 ? "50px" : "230px";
$(".ah-logo").animate(
{ width: toggleSize },200,"swing"
).promise().done(function(){
alert("Animation Complete!");
});
});
}
.ah-logo {
width: 230px;
float: left;
font-weight: 600;
font-size: 16px;
text-align: center;
overflow: hidden;
}
a {
line-height: 50px;
display: block;
}
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<div class="ah-logo">
Admin
</div>

Why does this popup add multiple overlay <div> to the DOM tree for no apparent reason?

I am using popup.js to display content inside a popup. However, if I am executing the basic example, this is what I am getting:
What you see here is the popup with some uninteresting content, but you can also see that <div class="popup_cont" ..> has been added several times to the DOM tree. The result is that I have to click (here) 7 times to get rid of the popup. Each click removes one of those overlays..
I have no idea why this is happening. This is how I embed the popup:
<div id="btn-help" class="toy-button">
<span lang="en">
HELP
</span>
</div>
And this is how it gets invoked:
/**
* Callback to display help window.
* #private
* #memberOf module:cpu-controlls_controller
*/
_onHelpButtonClicked = function() {
debug('cpu-controlls.controller _onHelpButtonClicked()');
var options = { content : "hallo.html" };
$('.default_popup').popup(options);
};
Where the hallo.html is just a .html file with a lot of "Hello World!" messages.
Any idea how I can solve this?
It seems like you initialize the popup plugin every time the user clicks on the button, so the first time it will work okay, but with every next click you will have more and more popups to close.
Put the initialization in the document.ready() function, and out of the click handler.
There are two different ways to popup the window (in any case I use always full url path):
/*-------------------------------
POPUP.JS
Simple Popup plugin for jQuery
#author Todd Francis
#version 2.2.3
-------------------------------*/
;(function(b,t){b.fn.popup=function(h){var q=this.selector,m=new b.Popup(h);b(document).on("click.popup",q,function(n){var k=h&&h.content?h.content:b(this).attr("href");n.preventDefault();m.open(k,void 0,this)});return this.each(function(){b(this).data("popup",m)})};b.Popup=function(h){function q(a){var d;b.each(a,function(a,c){if(c)return d=c,!1});return d}function m(a){return"function"===typeof a?"function":a instanceof b?"jQuery":"#"===a.substr(0,1)||"."===a.substr(0,1)?"inline":-1!==b.inArray(a.substr(a.length-
3),u)?"image":"http"===a.substr(0,4)?"external":"ajax"}function n(c){r&&r.fadeOut("fast",function(){b(this).remove()});var d=!0;void 0===f&&(d=!1,f=b('<div class="'+a.o.containerClass+'">'),p=b(a.o.markup).appendTo(f),b(a.o.closeContent).one("click",function(){a.close()}).appendTo(f),b(t).resize(a.center),f.appendTo(b("body")).css("opacity",0));var e=b("."+a.o.contentClass,f);a.width?e.css("width",a.width,10):e.css("width","");a.height?e.css("height",a.height,10):e.css("height","");p.hasClass(a.o.contentClass)?
p.html(c):p.find("."+a.o.contentClass).html(c);d?a.o.replaced.call(a,f,g):a.o.show.call(a,f,g)}function k(a,d){var b=(new RegExp("[?&]"+a+"=([^&]*)")).exec(d);return b&&decodeURIComponent(b[1].replace(/\+/g," "))}var a=this,u=["png","jpg","gif"],l,s,g,f,r,p;a.ele=void 0;a.o=b.extend(!0,{},{backClass:"popup_back",backOpacity:.7,containerClass:"popup_cont",closeContent:'<div class="popup_close">×</div>',markup:'<div class="popup"><div class="popup_content"/></div>',contentClass:"popup_content",
preloaderContent:'<p class="preloader">Loading</p>',activeClass:"popup_active",hideFlash:!1,speed:200,popupPlaceholderClass:"popup_placeholder",keepInlineChanges:!0,modal:!1,content:null,type:"auto",width:null,height:null,typeParam:"pt",widthParam:"pw",heightParam:"ph",beforeOpen:function(a){},afterOpen:function(){},beforeClose:function(){},afterClose:function(){},error:function(){},show:function(a,b){var e=this;e.center();a.animate({opacity:1},e.o.speed,function(){e.o.afterOpen.call(e)})},replaced:function(a,
b){this.center().o.afterOpen.call(this)},hide:function(a,b){void 0!==a&&a.animate({opacity:0},this.o.speed)},types:{inline:function(c,d){var e=b(c);e.addClass(a.o.popupPlaceholderClass);a.o.keepInlineChanges||(s=e.html());d.call(this,e.children())},image:function(c,d){var e=this;b("<img />").one("load",function(){var a=this;setTimeout(function(){d.call(e,a)},0)}).one("error",function(){a.o.error.call(a,c,"image")}).attr("src",c).each(function(){this.complete&&b(this).trigger("load")})},external:function(c,
d){var e=b("<iframe />").attr({src:c,frameborder:0,width:a.width,height:a.height});d.call(this,e)},html:function(a,b){b.call(this,a)},jQuery:function(a,b){b.call(this,a.html())},"function":function(b,d){d.call(this,b.call(a))},ajax:function(c,d){b.ajax({url:c,success:function(a){d.call(this,a)},error:function(b){a.o.error.call(a,c,"ajax")}})}}},h);a.open=function(c,d,e){c=void 0===c||"#"===c?a.o.content:c;if(null===c)return a.o.error.call(a,c,l),!1;void 0!==e&&(a.ele&&a.o.activeClass&&b(a.ele).removeClass(a.o.activeClass),
a.ele=e,a.ele&&a.o.activeClass&&b(a.ele).addClass(a.o.activeClass));if(void 0===g){g=b('<div class="'+a.o.backClass+'"/>').appendTo(b("body")).css("opacity",0).animate({opacity:a.o.backOpacity},a.o.speed);if(!a.o.modal)g.one("click.popup",function(){a.close()});a.o.hideFlash&&b("object, embed").css("visibility","hidden");a.o.preloaderContent&&(r=b(a.o.preloaderContent).appendTo(b("body")))}d=q([d,a.o.type]);l=d="auto"===d?m(c):d;a.width=a.o.width?a.o.width:null;a.height=a.o.height?a.o.height:null;
if(-1===b.inArray(d,["inline","jQuery","function"])){e=k(a.o.typeParam,c);var f=k(a.o.widthParam,c),h=k(a.o.heightParam,c);d=null!==e?e:d;a.width=null!==f?f:a.width;a.height=null!==h?h:a.height}a.o.beforeOpen.call(a,d);a.o.types[d]?a.o.types[d].call(a,c,n):a.o.types.ajax.call(a,c,n)};a.close=function(){a.o.beforeClose.call(a);"inline"===l&&a.o.keepInlineChanges&&(s=b("."+a.o.contentClass).html());void 0!==g&&g.animate({opacity:0},a.o.speed,function(){a.cleanUp()});a.o.hide.call(a,f,g);return a};a.cleanUp=
function(){g.add(f).remove();f=g=void 0;b(t).unbind("resize",a.center);a.o.hideFlash&&b("object, embed").css("visibility","visible");a.ele&&a.o.activeClass&&b(a.ele).removeClass(a.o.activeClass);var c=b("."+a.o.popupPlaceholderClass);"inline"==l&&c.length&&c.html(s).removeClass(a.o.popupPlaceholderClass);l=null;a.o.afterClose.call(a);return a};a.center=function(){f.css(a.getCenter());g.css({height:document.documentElement.clientHeight});return a};a.getCenter=function(){var a=f.children().outerWidth(!0),
b=f.children().outerHeight(!0);return{top:.5*document.documentElement.clientHeight-.5*b,left:.5*document.documentElement.clientWidth-.5*a}}}})(jQuery,window);
$(function () {
// first method
$('.default_popup').popup();
// second method
$('.default_popup1').click(function(e) {
e.preventDefault();
var popup = new $.Popup();
popup.open('http://stackoverflow.com/');
});
});
/*-------------------------------
POPUP.CSS
-------------------------------*/
.popup_back {
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
z-index: 100;
}
.popup_cont {
position: fixed;
z-index: 102;
}
.preloader {
z-index: 101;
}
/*---------------------
EDIT BELOW
*/
.popup_close {
color: #888;
cursor: pointer;
position: absolute;
padding: 5px;
right: 5px;
top: 0;
}
.popup_close:hover {
color: #111;
}
.popup_back {
cursor: pointer;
background-color: #222;
}
div.popup {
background: #fff;
padding: 25px;
box-shadow: 0 3px 10px #222;
}
.preloader {
left: 50%;
margin: -10px 0 0 -25px;
position: fixed;
top: 50%;
}
<script src="//code.jquery.com/jquery-1.11.3.js"></script>
<div id="btn-help" class="toy-button">
<span lang="en">
HELP1
</span>
</div>
<div id="btn-help1" class="toy-button">
<span lang="en">
HELP2
</span>
</div>

Count back percentage using JQuery

I have the code below where I'd like to the numbers count back to 0% once hover the object out. Also I can't figure our how to make the value disappear again as it was on load. Could you please help me solve this.
Thanks in advance.
HTML
<div class="container">
<div class="fill" data-width="80%"></div>
</div>
<div class="container">
<div class="fill" data-width="50%"></div>
</div>
CSS
.container {
position: relative;
width: 300px;
height: 30px;
background-color: blue;
margin: 10px auto;
}
.fill {
height: 100%;
width: 0;
background-color: red;
line-height: 30px;
text-align: left;
z-index: 1;
text-align: right;
}
JQuery
$(function() {
$('.container').hover( function(){
var width=$(this).find(".fill").data('width');
$(this).find(".fill").animate({ width: width }, {
duration:800,
step: function(now, fx) {
$(this).html(Math.round(now) + '%');
}
});
},
function(){
$(this).find(".fill").animate({ "width": "0px" }, 800);
});
});
jsFiddle http://jsfiddle.net/zp8pe069/
jsBin demo
CSS: set overflow: hidden to .fill to prevent the text being visible after the animation ends.
HTML: remove % from the data attribute
JS and here you go. all you need:
$('.container').hover(function( e ){
var $fill = $(this).find(".fill");
var width = $fill.data('width');
$fill.stop().animate({width: e.type=="mouseenter" ? width+"%" : "0%" }, {
duration : 800,
step : function(now) {
$(this).html(Math.round(now) + '%') ;
}
});
});
Note also the use of the .stop() method, if you hover multiple time hysterically :) it'll prevent endless animations.

Trouble in synchronising and/or adding captions to images using caroufredsel plugin

I am new to this so please bear with me if my question is obviously stupid. I am trying to incorporate the slideshow as shown in this site using caroufredsel http://coolcarousels.frebsite.nl/c/48/
Now I needed to add captions to the images. so after trying to tweak the code unsuccessfully, I created a workaround where I created another carousel for just the captions and synchronized it with the main carousel. It worked that the captions appeared just fine but now I am not able to synchronize it with the click function/feature on the main carousel. if I comment the click function out , it works splendidly, but I need that click function. what am I doing wrong or is there an easier way to do what I want. I went thru the documentation and tried to incorporate a new div with id "item". but then the entire "pager" section disappears etc. I will include the full code here. thanks in advance for the help.
my css looks like this::
html, body {
height: 100%;
padding: 0;
margin: 0px;
}
body {
min-height: 400px;
}
#wrapper {
width: 697px;
height: 400px;
margin: -155px 0 0 -330px;
position: absolute;
top: 270px;
left: 50%;
box-shadow: 0px 1px 20px #c5a101;
border:3px solid #c5a101;
background-color: rgba(246,217,90,0.9);
}
#carousel {
width: 580px;
height: 360px;
overflow: hidden;
position: relative;
z-index: 2;
float:left;
}
#carousel img {
display: block;
float: left;
}
#pager {
width: 112px;
height: 350px;
overflow: hidden;
position: absolute;
top: 0;
right: 0;
}
#pager div {
height: 81px;
width: 100px;
box-shadow: 0px 0px 5px #c5a101;
}
#pager img {
cursor: pointer;
display: block;
height: 81px;
width: 112px;
margin-bottom: 5px;
float: left;
border:3px solid #c5a101;
cursor:default;
}
#texts-wrapper {
width: 700px;
height: 50px;
float: left;
}
#texts > div {
width: 300px;
height: 50px;
position: relative;
float: left;
margin-top: auto;
}
#texts > div > div {
width: 700px;
position: absolute;
left: 2px;
bottom: 5px;
float: right;
padding-top: 25px;
}
#texts a {
color:#083377;
font-family:Trajan Pro;
font-size: 16px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0,0,0,0.4);
text-decoration: none;
outline: none;
display: block;
background-color: rgba(248,229,145,0.4);
border: 1px solid rgba(246,217,90,0.4);
width: 700px;
height: 85px;
padding-left: 10px;
}
#texts a:hover {
background-color: rgba(255,208,0,0.9);
box-shadow: 0px 2px 15px #c5a101;
color: rgba(227,75,76,0.7);
}
my html code looks like this::
<div id="wrapper">
<div id="inner">
<div id="carousel">
<img src="img/building.jpg" width="580" height="350" />
<img src="img/guytalkingtokids.jpg" width="580" height="350" />
<img src="img/group.jpg" width="580" height="350" />
<img src="img/oath.jpg" width="580" height="350" />
<img src="img/finalists.jpg" width="580" height="350" />
</div>
<div id="pager"></div>
</div>
<div id="texts-wrapper">
<div id="texts">
<div>
<a style="text-decoration:none; " href="blank.html" >
<div><p>The red building across the street.</p> </div></a>
</div>
<div>
<a style="text-decoration:none;" href="blank.html" >
<div><p>How yall doin? blah blah</p> </div></a>
</div>
<div>
<a style="text-decoration:none;" href="blank.html" >
<div><p>Lotsa ppl!.</p></div></a>
</div>
<div>
<a style="text-decoration:none;" href="blank.html" >
<div><p>I put another caption!</p></div></a>
</div>
<div>
<a style="text-decoration:none;" href="blank.html" >
<div> <p>Yay! We won?! How?!</p></div></a>
</div>
</div>
</div>
</div>
And my script tag looks like::
$(function() {
var $carousel = $('#carousel'),
$pager = $('#pager');
// gather the thumbnails
var $thumb = $( '<div class="thumb" />' );
$carousel.children().each(function() {
var src = $(this).attr( 'src' );
$thumb.append( '<img src="' + src.split('/large/').join('/small/') + '" />' );
});
// duplicate the thumbnails
for (var a = 0; a < $carousel.children().length - 1; a++) {
$pager.append( $thumb.clone() );
}
// create large carousel
$carousel.carouFredSel({
items: {
visible: 1,
width: 580,
height: 350
},
//auto:false,/* temporary: to stop automatic scrolling */
scroll: {
fx: 'directscroll',
pauseOnHover:true,
duration: 500,
timeoutDuration: 5500,
onBefore: function( data ) {
var oldSrc = data.items.old.attr('src').split('/large/').join('/small/'),
newSrc = data.items.visible.attr('src').split('/large/').join('/small/'),
$t = $thumbs.find('img:first-child[src="' + newSrc + '"]').parent();
$t.trigger('slideTo', [$('img[src="' + oldSrc + '"]', $t), 'next']);
}
}
});
// create thumb carousels
var $thumbs = $('.thumb');
$thumbs.each(function( i ) {
$(this).carouFredSel({
auto: false,
scroll: {
fx: 'directscroll'
},
responsive:true,
items: {
start: i+1,
visible: 1,
width: 112,
height: 89.6
}
});
// click the carousel---> comment out this portion to disable the click function on small images
$(this).click(function() {
var src = $(this).children().first().attr('src').split('/small/').join('/large/');
$carousel.trigger('slideTo', [$('img[src="' + src + '"]', $carousel), 'next']);
});
});
// comment out the click function and uncomment this section of #texts to have a synchronised carousel with captions but no click function
$('#texts').carouFredSel({
items: 1,
direction: 'left',
responsive:true,
auto: {
play: true,
duration: 500,
easing: 'quadratic',
timeoutDuration: 5500
}
});
});
Now I used jquery version 1.8.2 and caroufredsel version 6.2.1. thanks again for the help in advance. sorry if my code looks messy as well.Latest update as of 3/22/2014:: I went thru the documentation of the plugin CarouFredSel and stumbled upon one of the settable parameters/ configurations called "synchronise". If I understood it right, I can synchronise 2 carousels to respond to the same event. So i added the line of code "synchronise:{"#carousel"} into the text carousel to tell it to synchronise it with the main carousel...
$('#texts').carouFredSel({
items: 1,
direction: 'left',
responsive:true,
synchronise:{"#carousel"},/*This is the new line I added*/
auto: {
play: true,
duration: 500,
easing: 'quadratic',
timeoutDuration: 5500
}
});
Unfortunately that did not work as well. Now there is no timing pattern as well. everytime I click the small image it just went ahead in position at a random rate. So I am still stuck with the same problem if not making it worse. Thanks for the help in advance.
After fighting with the problem for more than a week, I was able to figure out a solution to my problem. Now it may not be the best solution but it worked and hence I am posting it so that in future if somebody else has the same or similar problem, it may be of help.Now if anyone came up with a solution that works better, I would still like you to post it here for I may want to learn what you did, why you did it and learn from the experience. I dont claim to be an expert programmer. I am still learning and this site has been a great learning tool for me so far.Anyway coming back to the problem, I added this piece of code...
//sais try: synchronise texts and carousel to work together and on click
var index = $(this).triggerHandler( 'currentPosition' );
if ( index == 0 ) {
index = $(this).children().length;
}
// trigger the titles carousel
$('#texts').trigger('slideTo', [ index, 'next' ]);
right here...
// create large carousel
$carousel.carouFredSel({
items: {
visible: 1,
width: 580,
height: 350
},
//auto:false,/* temporary: to stop automatic scrolling */
scroll: {
fx: 'directscroll',
pauseOnHover:true,
duration: 500,
timeoutDuration: 3500,
onBefore: function( data ) {
var oldSrc = data.items.old.attr('src').split('/large/').join('/small/'),
newSrc = data.items.visible.attr('src').split('/large/').join('/small/'),
$t = $thumbs.find('img:first-child[src="' + newSrc + '"]').parent();
$t.trigger('slideTo', [$('img[src="' + oldSrc + '"]', $t), 'next']);
/* [ the code goes here!]*/
now with that i was able to synchronise the carousels (#carousel, #texts) together to work with the click function/feature as well. Also I had tried to synchronise the carousel using a synchronise function thats in carouFredSel. Well take that out. It did not work.I dont know if this is going to be useful to anyone else but if it did, thats great. But again if somebody came up with a better solution please do let me know as well. Thanks. Keep up the goo work

Drop Down Animate Contact Box

I have been looking all day for a way to make a contact form similar to the one on this site: http://45royale.com/
If you click on the contact button a black background fades in and the from drops down using an ease function. I have been picking through the code trying to see what to do but I am stuck and I have also been looking and other javascript pop ups but so far it seems they only use php for the form however this one calls a html.
Any suggestions?
Here is something like the form in the example: http://jsfiddle.net/ep39v/3/.
And the source:
HTML
<div class="form"></div>
<button id="showFormBtn">Show form</button>
​
JavaScript
var form = $('.form');
$('#showFormBtn').click(function () {
fadeBackground(showForm);
});
(function () {
form.css({
top: -form.height(),
left: ($(document.body).width() - form.width()) / 2
});
}());
function fadeBackground(callback) {
var background = $('<div class="background"></div>');
$(document.body).append(background);
background.fadeTo(300, 0.5, function () {
if (typeof callback === 'function') {
callback();
}
});
}
function showForm() {
var form = $('.form');
form.animate({ top: 10 }, 1500, 'easeOutElastic');
}
​
CSS
.form {
width: 30%;
height: 40%;
background: black;
position: absolute;
}
body {
height: 100%;
}
.background {
height: 100%;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
background: black;
opacity: 0;
}​
May be you need to change only the easing.

Categories