Toggle between two numbers via a variable - javascript

Dragable width which upon being dragged sets a var;
var globaltest = 400;
It can also show/hide with animate so set the width;
var QSW-SW = $(".Quick-Sidebar-Wrapper").width() == globaltest ? "0" : globaltest;
alert(QSW-SW);
The rest...
$('.Quick-Sidebar-Wrapper').animate({
width: QSW-SW + "px"
}, {
duration: 1000,
direction: 'left',
easing: 'easeOutBounce'
});
This part breaks my script;
var QSW-SW = $(".Quick-Sidebar-Wrapper").width() == globaltest ? "0" : globaltest;
alert(QSW-SW);
And no alert comes up of which I placed there as a test.

QSW-SW is not a valid variable name. Javascript thinks you are trying to subtract. Try using an underscore instead.

Related

jquery slide div by changing margin

I'm making left/right buttons to make a div slide. It slides by changing the left margin. What I'm trying to do is have it check the left margin and then add/subtract pixels to it. So when the page loads, left margin should be 0. Then you click the button and it checks the margin, finds it's 0, adds 150 and sets the left margin to 150. And then if you click it again, it checks the margin, finds it's 150 and adds another 150 and sets the margin to 300.
It succeeds in moving the margin from 0 to 150, but i can't get it to go to 300. I'm thinking it's not able to determine the margin correctly. Any ideas how I can fix this? Thanks!
$('#left').click(function(){
var pos=$('#contentarea').css("margin-left").replace('px', '');
pos=pos+150;
$('#contentarea').animate({ 'margin-left': '-' + pos + 'px'}, 1000);
return false;
});
There is no need to get current margin-left value, you can use the '+=%value%' and '-=%value%' operators. This will add/substract from the current value the specified value.
$('#left').click(function(){
$('#contentarea').animate({ 'margin-left': '+=150px'}, 1000);
return false;
});
try this,
use for Get Margin
$('#contentarea').css("margin-left")
it will return margin default is "PX".
Use For Set Margin
$('#contentarea').css("margin-left","Your Size");
Default size is "PX" not need to provide size with "PX".
Try this function
$(document).ready(function () {
$('#contentarea').css("margin-left", "0");
});
$('#left').click(function () {
var pos = $('#contentarea').css("margin-left");
var size = 0;
if (pos == "0px") {
$('#contentarea').css("margin-left", "150");
}
else {
size = parseInt(pos.slice(0, -2));
size = size + 150;
}
var pos = $('#contentarea').css("margin-left", size);
$('#contentarea').animate({ 'margin-left': '-' + pos }, 1000);
return false;
})
Use parseInt instead of replace to get css margin left value.
$('#left').click(function(){
var pos = parseInt($('#contentarea').css("margin-left")) + 150;
$('#contentarea').animate({'margin-left' : '-' + pos + 'px'}, 1000);
return false;
});

How to re-position a Bootstrap Popover after dynamic content insertion?

So basically whenever I am loading a Bootstrap Popover with an empty content option and inserting content into it dynamically, the popover loses its correct position.
For example:
$('td.chartSection').each(function () {
var $thisElem = $(this);
$thisElem.popover({
placement: 'top',
trigger: 'hover',
html: true,
container: $thisElem,
delay: {
hide: 500
},
content: ' '
});
});
//After popup is shown, run this event
$('td.chartSection').on('shown.bs.popover', function () {
var $largeChart = $(this).find('.popover .popover-content');
//Insert some dummy content
$largeChart.html("dfjhgqrgf regqef f wrgb wrbgqwtgtrg <br /> wfghjqerghqreg fbvwqbtwfbvfgb <br />efgwetrg");
});
My Question:
Is there a method that can recalculate the popovers position such as $('td.chartSection').popover('recalculate').
Or is there another way to re-position the popover without manually doing this with CSS styles?
WORKING DEMO
Using Bootstrap v3.3.7:
You can extend the Popover constructor to add support for a re-positioning function. You can place this script below where you load bootstrap.
JSFiddle Demo
<script src="bootstrap.js"></script>
<script type="text/javascript">
$(function () {
$.fn.popover.Constructor.prototype.reposition = function () {
var $tip = this.tip()
var autoPlace = true
var placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement === 'bottom' &&
pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement === 'top' &&
pos.top - actualHeight < viewportDim.top ? 'bottom' : placement === 'right' &&
pos.right + actualWidth > viewportDim.width ? 'left' : placement === 'left' &&
pos.left - actualWidth < viewportDim.left ? 'right' : placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
}
})
</script>
Then in your script whenever you need to reposition your tooltip after inserting content. You can just call:
$element.popover('reposition')
No, there isn't a recalculate and there's really no easy way to do it. That said, you can dynamically inject the popovers this way:
$('td.chartSection').on('mouseenter', function() {
var myPopOverContent = 'This is some static content, but could easily be some dynamically obtained data.';
$(this).data('container', 'body');
$(this).data('toggle', 'popover');
$(this).data('placement', 'top');
$(this).data('content', myPopOverContent);
$(this).popover('show');
});
$('td.chartSection').on('mouseout', function() {
$(this).popover('hide');
});
Just replace all of your js in your fiddle with the above and check it out...
I just called
button.popover('show');
And it re-positioned it.
window.dispatchEvent(new Event('resize'));
This works for me.
I had a similar situation where I had a popover which already contained some HTML (a loading spinner) and I was changing the content when an ajax call returned. In my ajax callback function, this was the code I used to change the positioning so it remained centred:
var originalHeight = $(popover).height();
$(popover).find('.popover-content').html(data);
var newHeight = $(popover).height();
var top = parseFloat($(popover).css('top'));
var changeInHeight = newHeight - originalHeight;
$(popover).css({ top: top - (changeInHeight / 2) });
I used this code to adjust the height off the popover when it's already loaded to the page:
var popover = $(this).closest('.popover');
var sender = popover.prev();
var adjustment = (sender.position().top - popover.height()) + 15;
popover.css({ top: adjustment });
Variable sender is the target where the popover is centred from.
this is inspired by #AlexCheuk answer above, but I needed a solution using Bootstrap 2. Also, in my project I didn't need to change popovers' placement, so I cut that out.
$(function() {
$.fn.popover.Constructor.prototype.reposition = function () {
console.log('popover reposition is called');
var $tip = this.tip();
var placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement;
var pos = this.getPosition();
var actualWidth = $tip[0].offsetWidth;
var actualHeight = $tip[0].offsetHeight;
function getCalculatedOffset (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width };
}
var calculatedOffset = getCalculatedOffset(placement, pos, actualWidth, actualHeight);
this.applyPlacement(calculatedOffset, placement);
console.log(this);
};
});
To call it:
$element.popover('reposition')
If the popover's position is "top" (as in the question), you can just adjust its absolute positioning from the top of the page.
I've created a function to work out the height of the popover, and then shift it up on the page by its height.
function adjustPopoverHeight($popoverElement) {
var height = $popoverElement.height();
var adjustment = 0 - height - 4;
$popoverElement.css({ top: adjustment });
}
and use with an ajax request to get data:
$.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
dataType: 'json'
}).done(function(dat) {
//set the popover content to whatever you like
//adjust height of popover
var $popoverElement = $('.popover');
adjustPopoverHeight($popoverElement);
})
I took the concept of jme11's answer and updated for Bootstrap 3.3.2+
$('button')
.popover({
trigger: 'manual',
html: true,
container: 'body',
})
.click(function() {
var $this = $(this);
var popover_obj = $this.data('bs.popover');
if (popover_obj.tip().hasClass('in')) {
popover_obj.hide();
} else {
var opts = popover_obj.options;
opts.content = $('<div/>').text('hello world');
popover_obj.init('popover', $this, opts);
popover_obj.show();
}
})
;
There's a method called setContent on the popover object, but for some reason it wasn't working for me. If you'd like to try, it would look like this:
popover_obj.setContent($('<div/>').text('hello world'));
After a Popover content update, if you scroll up or down on page content, Popover does an auto-positioning and is readable again, so a simpler workaround to re-position the Popover after dynamic content update is to scroll down and up for 1 pixel on the page via pure javascript:
var y = $(window).scrollTop(); //your current y position on the page
$(window).scrollTop(y+1).scrollTop(y-1);
I experienced positioning issues after dynamically inserting other elements in the DOM and I solved them using the container option. By default my popovers were attached to body.
Attaching them to the closest container solved the position problems.
<div id="test">
<span
data-container="#test" data-toggle="popover" data-placement="top" title="Help"
data-trigger="hover" tabindex="-1" data-html="true"
data-content="Some text">
</div>

Blind an element and change style css at same tyme

I'm working on my portfolio and need help to #blind an element and change style property at bottom element at same time.
The idea is to exist a fixed space between the two elements, like this one EXAMPLE
If u see the example when you click, a bar appears and the space between two remains. Then if u click again the element hide and the space remains the same!!
"#contacts" -> element i want to blind
"#line" -> element i want change the top property
Im trying to resolve using jquery function called "blind":
$("#contacts").toggle("blind", {direction : "vertical"}, 500);
Then i get the top value of #line with if:
var line = $( "#line" );
var position = line.position();
var top = position.top;
if(top == value){
$("#line").animate({top:'100px'}, time);
} else { ... }
Please help!!
I'd do it without jQuery UI by using the top value and z-index
var contactTop = 85,
nextTop;
$(".oppen").click(function() {
nextTop = nextTop !== contactTop ? contactTop : 5;
$("#contacts").animate({top: nextTop}, 500);
.....
Demo
To stop the queuing you can apply the same technique on #line in addition to using jQuery's .stop
var contactTop = 85,
nextTop,
lineStart = 100,
lineEnd = 180,
lineTop = 100;
$(".oppen").click(function() {
nextTop = nextTop !== contactTop ? contactTop : 5;
$("#contacts").stop().animate({top: nextTop}, 500);
lineTop = lineTop !== lineStart ? lineStart : lineEnd;
$( "#line" ).stop().animate({top:lineTop}, 500);
});
Demo

Countdown using javascript

I'm trying to create a countdown for a quiz I created. The quiz will create a percentage and I am trying to create a JavaScript function that will count down from 100% to the users quiz score percentage.
Also is it possible to change the color of the percentage while it's counting down?
Example 100% Green and it starts to fade to red when it hits 59% and below?
What I am working with now:
<div id="counter">
</div>
var stop = 6;
for(i=1; i <= 100; i++) {
$('#counter').append('<p>' + i + '%');
}
$('#counter').cycle({
delay: 600,
fx: 'none',
backwards: true,
speed: 300,
timeout: 60,
autostop: 1,
autostopCount: stop,
});
Link:http://jsfiddle.net/joshsmith/WE3UA/4/
Thank You
This will make it change from pure green at 100% to pure red at 50%. I'm not sure if you wanted it to stay green all the way down to 60%. If you want that, then just put a ternary statement into the green function like this "return i > 60 ? 255 : Math.round(256*(i+40)/50-256)"
var stop = 60;
function green(i) { return Math.round(256*i/50-256); }
function red(i) { return 256-green(i); }
function toHex(c) { var h = c.toString(16); return h.length > 1 ? h : '0'+h; }
function color(i) { return i <= 50 ? 'f00' : toHex(red(i)) + toHex(green(i)) + '00'; }
for(i=1; i <= 100; i++) {
$('#counter').append('<p style="color: #' + color(i-1) + '">' + i + '%');
}
$('#counter').cycle({
delay: 600,
fx: 'none',
backwards: true,
speed: 300,
timeout: 60,
autostop: 1,
autostopCount: stop,
});
Looks like you'e already doing a pretty good job on the countdown itself.
You can easily animate colors using something like this jQuery color plugin:
https://github.com/jquery/jquery-color
Since your cycle plugin just iterates through a lot of elements that have already been created, you can simply set the paragraphs for valeus below 59 to whatever value you want.
You get a after event which gets fired after every tick. You could use that to change the color of your text.
var stop = 6;
for(i=1; i <= 100; i++) {
$('#counter').append('<p>' + i + '%');
}
var nCounter = 0;
$('#counter').cycle({
delay: 600,
fx: 'none',
backwards: true,
speed: 300,
timeout: 60,
autostop: 1,
autostopCount: stop,
after: function(currSlideElement, nextSlideElement, options, forwardFlag)
{
nCounter++
var percent = nCounter /stop * 100;
if(percent < 10)
{
$('#counter').css("color", "red");
}
}
});
U Just Need to Make Increment In RGB Values According to User Progress.
Try it out :)
var c1=c2=c3=0;
for(i=1; i <= 100; i++)
{
document.getElementById("#counter").style.color=rgb(c1,c2,c3);
if(i>30 && i<60)
{
c2++;
}
}

Shake a login form on error

I have successfully built a login form using ajax and want to add a shake effect to the form when the user enters incorrect details. I have the function in place that will fire but just need to build the jquery effect (note I know of jquery UI but don't want to use it! I don't want to use ANY plugins for this)
So far I have:
function shakeForm() {
var p = new Array(15, 30, 15, 0, -15, -30, -15, 0);
p = p.concat(p.concat(p));
$('form').css('left',p);
}
From what I understand I need to loop the array of values but how do I do that? Note that the element form has a position of relative already. So it's just a case of running those values as the left value in a random sequence?
Thanks
Why bother?
Animations are queued.
More - instead a left attribute you can use margin-left what prevents to adding position attribute :)
function shakeForm() {
var l = 20;
for( var i = 0; i <= 10; i++ ) {
$( 'form' ).animate( {
'margin-left': '+=' + ( l = -l ) + 'px',
'margin-right': '-=' + l + 'px'
}, 50);
}
}
Its better to use CSS to this instead of JS. CSS uses less resources(is faster) and its simpler.
You can find good (and 'ready to use') examples here: https://daneden.me/animate/
I have made a plugin for this .. check it http://static.mbiosinformatica.com.br/jQuery/
Is it working in IE ( 7 , 8 , 9 ) , Chrome and Firefox.
And, you can apply a callback function, to show error message .. or anything else.
$('#div').shake({
positions : { 'L' : 50 , 'R' : 50 } , // shake only left and right (U,L,R,D)
rotate : false , // rotate div on shake .. true/false
parent : false // shake parent div .. true/false
}, function(){ /* do something */ });
In the positions, you can send array too, just: positions: [ [ 'L', 50 ... ] ]
This value '50' its the shake distance from original position ..
To change timeout ( delay ) and effect duration, you have to set timeout: [you timeout .. / delay ] and the effect times .. interval: ...
mmm why use native js if jquery animate() is available... you try recurring like this:
var p = new Array(15, 30, 15, 0, -15, -30, -15, 0);
function shakeForm(index) {
if(typeof index === "undefined") index = 0;
if(typeof p[index] === "undefined") return false;
$("form").animate({
"left": p[index]
}, function() {
shakeForm(index + 1);
});
}
For those of you who are stubborn (like me) and hate libraries...
var e = document.getElementById('dividname');
e.style.marginLeft='8px';
setTimeout(function(){e.style.marginLeft='0px';},100);
setTimeout(function(){e.style.marginLeft='8px';},200);
setTimeout(function(){e.style.marginLeft='0px';},300);
then in your css:
.shakeClass{
transition: margin 100ms;
}
loop throw the array using jQuery.each: http://jsfiddle.net/N8F7Z/1/
function shakeForm() {
var p = "15 30 15 0 -15 -30 -15 0".split(" ");
$.each(p, function(key, value) {
var delay = 100;
setTimeout(function() {
$("form").css("left", value + "px");
}, delay*key);
});
}
A simple way to make an array is splitting a string with every space:
var p = "15 30 15 0 -15 -30 -15 0".split(" ");
The delay between each step:
var delay = 100;
Using setTimeout(function() {...}, theTimeBeforeFiring )
theTimeBeforeFiring = delay * key
key is the key the value has in the array:
key = 0, 1, 2, 3
jquery animations are queued by default, so you just need to call animate for each element of the array:
function shakeForm() {
var p = [15, 30, 15, 0, -15, -30, -15, 0];
var x = $('form').offset().left;
var speed = 40;
$.each(p, function() {
$('form').animate({'left': x + this}, speed);
});
}
Example: http://jsfiddle.net/3qdFL/
The examples above change the original position of the element.
function shakeForm() {
var margin = 15;
var speed = 50;
var times = 5;
for( var i = 0; i < times; i++ ){
$( "form" ).animate( { 'margin-left': "+=" + ( margin = -margin ) + 'px' }, speed);
$( "form" ).animate( { 'margin-right': "+=" + ( margin = -margin ) + 'px' }, speed);
$( "form" ).animate( { 'margin-right': "+=" + ( margin = -margin ) + 'px' }, speed);
$( "form" ).animate( { 'margin-left': "+=" + ( margin = -margin ) + 'px' }, speed);
}
}
demo here http://jsfiddle.net/UW6tN/1/
why not use css3 animations? less over head in my opinion. There so many plugins that exist because so many reinvent the wheel... I searched for the same thing and got 20 results of forums, and jquery plugins(yet another script to add)..but I found this and it works of coarse.
not my answer but it pure css3!
CSS animation similar to Mac OS X 10.8 invalid password "shake"?

Categories