Overwriting CSS : Display none property with jquery - javascript

For an element defined as display:none in css I am trying to run a function which tries to display the element using .show(), code below:
CSS
.element {
position: absolute;
display: none;
left: 0;
top: 0;
}
HTML
<div class="element">Some content here</div>
<div class="element">Some content here</div>
jQuery
var c = $('.element');
c.each(function () {
c.css({
'left': dleft + 'px'
});
c.css({
'top': dtop + 'px'
});
c.setTimeout(function () {
c.show(1000);
}, sduration);
All the variables are getting populated I have checked by alerting all of them and given them default values as well, but somehow the element is not being shown after the timeout.

There seems to be two problems in the code you have written. you have not closed the .each() loop .. Also setTimeout is a global function.. .. Check this
var dleft = 40;
var dtop = 40;
var sduration = 1000;
var c = $('.element');
c.each(function() {
c.css({
'left': dleft + 'px',
'top': dtop + 'px'
});
});
setTimeout(function() {
c.show(1000);
}, sduration);​
Check this FIDDLE

setTimeout is a global function.
var c = $('.element');
c.each(function () {
c.css({ 'left': dleft + 'px', 'top': dtop + 'px' });
setTimeout(function () {
c.show(1000);
}, sduration);
});
Demo: http://jsfiddle.net/S7nw3/

If you need to delay when the elements are being shown, you can also make use of the jQuery .delay() function.
c.each(function() {
c.css({
'left': dleft + 'px',
'top': dtop + 'px'
});
});
c.delay(1000).show();

Related

jQuery content scroller fails to show list items after first one

So I have a news scroller which rotates through an array of news items, fading them in and out. For some reason, on mobile devices, it malfunctions after the first item is displayed, hiding all other items. Chrome DevTools tells me that they fail to show because their display is set to none. My question is, why would this be working on desktops, but malfunctioning on mobile devices (namely iPhone 6/7/8)? Here is the code used to show the items:
newsArr = ['Item 1','Item 2','Item 3','Item 4'];
$.each(newsArr, function(i) {
$('ul#newsScroller').append('<li class="news-item">' + newsArr[i] + '</li>');
$('#allNewsDiv').append('<div class="all-news-item"><img src="https://dl.dropbox.com/s/r8nu1zb2gpzd92k/Ball%20Icon.png" alt="" style="float:left; margin-right:10px; position: relative; top: 2px;" width="20" height="20"><div class="all-news-item-text">' + newsArr[i] + '</div></div>');
});
// Determine the height of the li element and set the scroller to that height
var maxScrollerHeight = Math.max.apply(null, $('ul#newsScroller li').map(function() {
return $(this).outerHeight(true);
}).get());
$('#newsScroller').css({
'height': (maxScrollerHeight) + 'px',
'opacity': '1'
});
// Hide li elements initially
$('ul#newsScroller li').css({
'display': 'none'
});
(function() {
var newsItems = $(".news-item");
var newsItemsIndex = -1;
function showNextNewsItems() {
++newsItemsIndex;
newsItems.eq(newsItemsIndex % newsItems.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextNewsItems);
}
showNextNewsItems();
})();
https://jsfiddle.net/shaneswebdevelopment/k2ptfhqz/
I found an article about a problem with fading in/out on the iphone:
jQuery fadeIn Not Working on iPhones
Maybe you have to set the position of your list to relative.
newsArr = ['Item 1','Item 2','Item 3','Item 4'];
$.each(newsArr, function(i) {
$('ul#newsScroller').append('<li class="news-item">' + newsArr[i] + '</li>');
$('#allNewsDiv').append('<div class="all-news-item"><img src="https://dl.dropbox.com/s/r8nu1zb2gpzd92k/Ball%20Icon.png" alt="" style="float:left; margin-right:10px; position: relative; top: 2px;" width="20" height="20"><div class="all-news-item-text">' + newsArr[i] + '</div></div>');
});
// Determine the height of the li element and set the scroller to that height
var maxScrollerHeight = Math.max.apply(null, $('ul#newsScroller li').map(function() {
return $(this).outerHeight(true);
}).get());
$('#newsScroller').css({
'height': (maxScrollerHeight) + 'px',
'opacity': '1'
});
// Hide li elements initially
$('ul#newsScroller li').css({
'display': 'none',
'position': 'relative'
});
(function() {
var newsItems = $(".news-item");
var newsItemsIndex = -1;
function showNextNewsItems() {
++newsItemsIndex;
newsItems.eq(newsItemsIndex % newsItems.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextNewsItems);
}
showNextNewsItems();
})();
Problem solved!
I changed from using the display style attribute to using opacity. Each news item is set to position: absolute and faded in and out like so:
// Hide li elements initially
$('ul#newsScroller li').css({
'opacity': '0'
});
(function() {
var newsItems = $(".news-item");
var newsItemsIndex = -1;
function showNextNewsItems() {
++newsItemsIndex;
newsItems.eq(newsItemsIndex % newsItems.length)
.fadeTo(2000,1)
.delay(2000)
.fadeTo(2000,0,showNextNewsItems);
}
showNextNewsItems();
})();

Jquery not recognize on click function second time

I really need help.
Here's what I'm trying to do: I wanna create 3 div elements which are flying from top to bottom of div (#lang_flying_objects) and when i click "the right one" (by Id), I need to create three more. When I create them I assign them all class "snowflakes".
But I am only able to click on the first group and my onclick function recognize the right id, but when other group is created it won't trigger the onclick function.
PLEASE HELP ME.
Here is the code I'm using:
<script>
function fallingStuff() {
var $snowflakes = $(),
createFallingStuff = function () {
var $snowflake = $('<div class="snowflakes" id="first"></div>');
$snowflake.css({
'left': (Math.random() * ($('#lang_flying_objects').width()/3 - offset)) + 'px',
'top': (-(20 + offset)) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
var $snowflake2 = $('<div class="snowflakes" id="second" ></div>');
$snowflake2.css({
'left': (Math.random() * ($('#lang_flying_objects').width()/3 - offset) + $('#lang_flying_objects').width()/3) + 'px',
'top': (-(20 + offset)) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake2);
var $snowflake3 = $('<div class="snowflakes" id="third"></div>');
$snowflake3.css({
'left': (Math.random() * ($('#lang_flying_objects').width()/3 - offset) + 2*$('#lang_flying_objects').width()/3) + 'px',
'top': (-(20 + offset)) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake3);
$('#falling_zone').prepend($snowflakes);
},
runFalling = function() {
$snowflakes.each(function() {
var singleAnimation = function($flake) {
$flake.animate({
top: "500px",
opacity : "0"
}, 10000);
};
singleAnimation($(this));
});
};
createFallingStuff();
runFalling();
}
fallingStuff();
</script>
And here is my onclick function:
<script>
$('.snowflakes').on('click', function() {
var idInputed = $(this).attr('id');
if(idInputed == "first") //for example
{
fallingStuff();
}
});
</script>
Why it won't recognize the onclick function for second group of created divs?
Since the elements are created dynamically, you should use event delegation:
$(document).on('click', '.snowflakes', function() {
var idInputed = $(this).attr('id');
if(idInputed == "first") {
fallingStuff();
}
});

How to stop and reset few animated elements in object? (several separate animations)

I have created a few animations and each of them should be a separate slide on the main site slider.
Thats why, I've got from my boss an object structure (code below) and he said I should use it to those animations.
var RDAnimation = function(o){
var f = $.extend({
start: function() {
return true;
},
pause: function() {
return true;
},
reset: function() {
return true;
},
stop: function() {
if (this.pause()) {
return this.reset();
}
},
vars: {}
},o);
this.start = f.start;
this.pause = f.pause;
this.reset = f.reset;
this.stop = f.stop;
this.vars=f.vars;
};
But because I don't have a much of experience with working on objects, I just paste all of the animating function into 'start', just to see what will happen (code below).
var anim3=new RDAnimation({
start: function() {
var $this = this;
function bars() {
var barHeight = 0;
$('.chart-bar').each(function () {
barHeight = Math.floor(Math.random() * 100);
$(this).delay(1000).animate({
'height': barHeight + '%',
'min-height': '20px'},
700, function(){
bars();
});
});
}
var count = 0;
function badgeClone() {
var badge1 = $('.badge');
var badge2 = $('.badge').clone();
var badgeWidth = badge1.width();
var badgeHeight = badge1.height();
//badge1.text(count);
badge1.after(badge2);
badge2.css({
'line-height': '180px',
'text-align': 'center',
'font-size': '70px',
'font-weight': 'bold',
'color': '#fff',
'opacity':'0'
});
badge2.animate({
'width': badgeWidth * 2 + 'px',
'height': badgeHeight *2 + 'px',
'line-height': '360px',
'font-size': '140px',
'top': '-150px',
'right': '-100px'
},
100, "linear", function() {
if(count >= 9) {
count = 1
} else {
count++
}
badge2.text(count);
badge2.delay(300).animate({
'width': badgeWidth + 'px',
'height': badgeHeight + 'px',
'line-height': '180px',
'font-size': '70px',
'top': '-60px',
'right': '-40px',
'opacity': '1'},
100, "linear", function(){
badge1.fadeOut(600, function(){
$(this).remove();
});
});
});
}
bars();
var chartbars = $('.chart-bar');
$(chartbars).each(function(i) {
chartbar = chartbars[i];
var leftPos = i * 24 + 4;
$(chartbar).css({'left': leftPos + 'px'});
});
// ppl animations
var height = $('.person').height();
$('.person').css({'top': -height + 'px'});
var female = function(){
$('.female').fadeIn(300).animate({'top': '0px'}, 2500, function(){
male();
badgeClone();
$(this).delay(1000).fadeOut(500, function() {
$(this).css({'top': -height + 'px'});
});
});
};
var male = function(){
$('.male').fadeIn(300).animate({'top': '0px'},2500,function(){
badgeClone();
female();
$(this).delay(1000).fadeOut(500, function() {
$(this).css({'top': -height + 'px'});
});
});
};
male();
},
pause: function() {
var $this = this;
$('.chart-bar').stop();
},
reset: function() {
var $this = this;
$this.count = 0;
},
vars: {
}
});
And it's working! Animation will start when I run anim3.start. But now.. How can I stop it? Because I have to stop it when user chose another animated slide, and start it from beginning when user again chose this slide.
I've wrote a simple code, just for test.. But it doesnt work.
In code above I've wrote $('.chart-bar').stop(); in pause, to check if this will stop at least one chart-bar animation but it doesnt.
In reset I've wrote $this.count = 0; to reset number on the .badge element - but it doesnt work as well..
Obviously, to run those lines of code I've put a simple code on the bottom of script (code below).
$('#slider-2, #slider-3').hide();
$('.tour-slider').on('click', 'li a', function(e){
e.preventDefault();
$(this).closest('.slider').hide();
var sliderHref = $(this).attr('href');
$(sliderHref).fadeIn();
if(sliderHref == '#slider-1'){
anim1.start();
anim3.pause();
}else if(sliderHref == '#slider-2'){
anim2.start();
anim3.pause();
}else if(sliderHref == '#slider-3'){
anim3.reset();
anim3.start();
anim3.pause();
}
});
As you can see, I even run a anim3.pause(); at once, after I start it - just to check, if it will stop immediately - but even one chart-bar didn't stop..
So now, can somebody tell my please, how can I stop (and reset) these animated elements? I just need to get one working example and rest I can do by my own.
I will be grateful for any help
Cheers!
Ok, I found a solution.
1st of I modify a bars() function (add if statement)
function bars() {
var barHeight = 0;
var loop = true;
$('.chart-bar').each(function () {
barHeight = Math.floor(Math.random() * 100);
$(this).delay(1000).animate({
'height': barHeight + '%',
'min-height': '20px'},
700, function(){
if (loop) {
bars();
}
});
});
}
And then all I need was those two line of code added into my pause method:
pause: function() {
var $this = this;
$('#animation-3').find('*').stop(true, false);
$this.loop = false;
}
Thanks everyone for your time :)

how to include .ready() function in .load()

On my site, I am using a jquery script to make my site dynamic ( most part of the site is charged once, and while you navigates, only the main content will change). It uses .load() . Unfortunatly this function tends to negate any javascript/Jquery code that is called by the container which is dynamic. So I have to call them during the load .
Here is the code of script:
$(function () {
if (Modernizr.history) {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function () {
_link = $(this).attr("href");
history.pushState(null, null, _link);
loadContent(_link);
return false;
});
function loadContent(href) {
$mainContent
.find("#guts")
.fadeOut(200, function () {
$mainContent.hide().load(href + " #guts", function () {
// I call the script here.
$.getScript('tablecloth/tablecloth.js', function () {
tablecloth();
});
$.getScript('js/domtab.js', function () {
domtab.init();
});
// This one is the one which doesn't work.
$.getScript('js/onReady.js', function () {
});
$mainContent.fadeIn(200, function () {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
console.log(href);
$("nav a[href$=" + href + "]").addClass("current");
});
});
}
$(window).bind('popstate', function () {
_link = location.pathname.replace(/^.*[\\\/]/, ''); //get filename only
loadContent(_link);
});
} // otherwise, history is not supported, so nothing fancy here.
});
And I have a script for one page, that uses .click() function, onReady.js :
$(document).ready( function() {
var maxHeight = document.getElementById("flip1").scrollHeight;
var maxHeight2 = document.getElementById("fli1A").scrollHeight;
var parent = document.getElementById("flip-container");
var DivContainerHeight = $('#text1').scrollHeight;
$("#text_var").html(maxHeight2);
//alert(DivContainerHeight);
//document.getElementById('tooltip6').style.display = 'block';
document.getElementById('global').style.height = DivContainerHeight + 'px';
//$("#flip-tabs").css({ height: maxHeight+'px' });
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1300px'
});
$('#fl1A').on("click", function (e) {
$("#fli1A").show();
var maxHeight2 = document.getElementById("fli1A").scrollHeight;
//alert("New height: " + maxHeight2);
$("#text_var").html(maxHeight2);
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1000px'
});
});
$('#fl1B').on("click", function (e) {
$("#fli1B").show();
var maxHeight2 = document.getElementById("fli1B").scrollHeight;
//alert("New height: " + maxHeight2);
$("#text_var").html(maxHeight2);
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1000px'
});
});
$('#fl2A').on("click", function (e) {
$("#fli2A").show();
var maxHeight2 = document.getElementById("fli2A").scrollHeight;
//alert("New height: " + maxHeight2);
$("#text_var").html(maxHeight2);
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1000px'
});
});
$('#fl2B').on("click", function (e) {
$("#fli2B").show();
var maxHeight2 = document.getElementById("fli2B").scrollHeight;
//alert("New height: " + maxHeight2);
$("#text_var").html(maxHeight2);
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1000px'
});
});
$('#fl3A').on("click", function (e) {
$("#fli3A").show();
var maxHeight2 = document.getElementById("fli3A").scrollHeight;
//alert("New height: " + maxHeight2);
$("#text_var").html(maxHeight2);
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1000px'
});
});
$('#fl3B').on("click", function (e) {
$("#fli3B").show();
var maxHeight2 = document.getElementById("fli3B").scrollHeight;
//alert("New height: " + maxHeight2);
$("#text_var").html(maxHeight2);
$("#flip-tabs").css({
'height': maxHeight2 + 'px'
//'height': '1000px'
});
});
});
The code will work fine when I load directly for the first time, the page where I uses this code ( A.html), but if I load another page and then go to A.html again then it won't work anymore. It is as if the getscript will work the first time I load a page. Although tablcloth() and domtab() work fine for each page.
In the head of each page I have
<script type ="text/javascript" src="js/onReady.js"></script>
But I don't think it has any purpose.
Another question is it possible to make the script onReady load only when I load the page A.html ?
Instead of $(document).ready you could use function pageLoad(){}.
It's automatically called by the ScriptManager on a page, even on a postback.
I think that's your issue here, your changes doesn't get affected on a postback.
Hope this helps you.
Cheers
You can add events for dynamically created content in the doc ready function with jQuery's .on() method http://api.jquery.com/on/ this will prevent you from having to attach listeners on every load function call
I found the solution I remplaced the codes onReady.js by this :
this.tabHeight = function () {
codes......
};
window.onload = tabHeight;
And in the .load() I call it this way :
$.getScript('js/onReady.js', function () {
tabHeight();
});
In fact I just copied the way tablecloth did it.

flip the tooltip when approaching the margin using "Collision"

My tooltips are going outside of the boundaries of my page. I am using a jquery plugin called aToolTip. Here is my code:
(function($) {
$.fn.aToolTip = function(options) {
/**
setup default settings
*/
var defaults = {
// no need to change/override
closeTipBtn: 'aToolTipCloseBtn',
toolTipId: 'aToolTip',
// ok to override
fixed: false,
clickIt: false,
inSpeed: 200,
outSpeed: 100,
tipContent: '',
toolTipClass: 'defaultTheme',
xOffset: 5,
yOffset: 5,
onShow: null,
onHide: null,
},
// This makes it so the users custom options overrides the default ones
settings = $.extend({}, defaults, options);
return this.each(function() {
var obj = $(this);
/**
Decide weather to use a title attr as the tooltip content
*/
if(obj.attr('title')){
// set the tooltip content/text to be the obj title attribute
var tipContent = obj.attr('title');
} else {
// if no title attribute set it to the tipContent option in settings
var tipContent = settings.tipContent;
}
/**
Build the markup for aToolTip
*/
var buildaToolTip = function(){
$('body').append("<div id='"+settings.toolTipId+"' class='"+settings.toolTipClass+"'><p class='aToolTipContent'>"+tipContent+"</p></div>");
if(tipContent && settings.clickIt){
$('#'+settings.toolTipId+' p.aToolTipContent')
.append("<a id='"+settings.closeTipBtn+"' href='#' alt='close'>close</a>");
}
},
/**
Position aToolTip
*/
positionaToolTip = function(){
$('#'+settings.toolTipId).css({
top: (obj.offset().top - $('#'+settings.toolTipId).outerHeight() - settings.yOffset) + 'px',
left: (obj.offset().left + obj.outerWidth() + settings.xOffset) + 'px'
})
// added delay() call...
.stop().delay(1000).fadeIn(settings.inSpeed, function(){
if ($.isFunction(settings.onShow)){
settings.onShow(obj);
}
});
},
/**
Remove aToolTip
*/
removeaToolTip = function(){
// Fade out
$('#'+settings.toolTipId).stop().fadeOut(settings.outSpeed, function(){
$(this).remove();
if($.isFunction(settings.onHide)){
settings.onHide(obj);
}
});
};
/**
Decide what kind of tooltips to display
*/
// Regular aToolTip
if(tipContent && !settings.clickIt){
// Activate on hover
obj.hover(function(){
// remove already existing tooltip
$('#'+settings.toolTipId).remove();
obj.attr({title: ''});
buildaToolTip();
positionaToolTip();
}, function(){
removeaToolTip();
});
}
// Click activated aToolTip
if(tipContent && settings.clickIt){
// Activate on click
obj.click(function(el){
// remove already existing tooltip
$('#'+settings.toolTipId).remove();
obj.attr({title: ''});
buildaToolTip();
positionaToolTip();
// Click to close tooltip
$('#'+settings.closeTipBtn).click(function(){
removeaToolTip();
return false;
});
return false;
});
}
// Follow mouse if enabled
if(!settings.fixed && !settings.clickIt){
obj.mousemove(function(el){
$('#'+settings.toolTipId).css({
top: (el.pageY - $('#'+settings.toolTipId).outerHeight() - settings.yOffset),
left: (el.pageX + settings.xOffset)
});
});
}
}); // END: return this
};
})(jQuery);
How do I modify my tooltips to flipfit flip when approaching the right margin? Right now I they disappear off into the right and top margins. I also need them to wrap after 350px.
I tried adding the following to the function with no results:
max-width: 350px,
collision: "flipfit flip",
What am I doing wrong?
your issue is right here:
positionaToolTip = function(){//this is not toggling between the two.
$('#'+settings.toolTipId).css({
top: (obj.offset().top - $('#'+settings.toolTipId).outerHeight() - settings.yOffset) + 'px',
left: (obj.offset().left + obj.outerWidth() + settings.xOffset) + 'px'
})
// added delay() call...
.stop().delay(1000).fadeIn(settings.inSpeed, function(){
if ($.isFunction(settings.onShow)){
settings.onShow(obj);
}
});
},
maybe adding something like this would work:
var $tooltip = $('#' + settings.toolTipId),
$win = $(window),
winLeft = $win.scrollLeft(),
objWidth = obj.outerWidth(),
tipWidth = $tooltip.outerWidth(),
offset = $obj.offset(),
ttWidth = $tooltip.outerWidth(),
ttHeight = $tooltip.outerHeight();
$win.width() < (offset.left - winLeft + objWidth + tipWidth + ttWidth) ?
$tooltip//reversed (to left)
.addClass("reversed")
.css({
left: offset.left - winLeft - tipWidth - ttWidth,
top: offset.top - $win.scrollTop() + $obj.outerHeight() / 2 + ttHeight
})
:
$tooltip//standard (to right)
.css({
left: offset.left - winLeft + objWidth + ttWidth,
top: offset.top - $win.scrollTop() + $obj.outerHeight() / 2 + ttHeight
});

Categories

Resources