Decrement value by javascript variable inside the css property - javascript

I wanna move content with animation.
There's an animation in the jquery function, like that:
.on('click', '.btn', function () {
var contentWidth = $(window).width() - $('.sidebar').width();
$( ".content" ).animate({
left: "+=1000",
}, 5000, function() {
// moving content function
}
);
});
So, because I have various positions of content, I need to use this value in the variable contentWidth. How I can set this value in a variable and decrement the left value every time when I call a function?
Something like left: "+=contentWidth" doesn't work. Is where I make mistake?

Not sure if i got it but...
maybe you could use string interpolation
.on('click', '.btn', function () {
var contentWidth = $(window).width() - $('.sidebar').width();
$( ".content" ).animate({
left: `+=${contentWith}`,
}, 5000, function() {
// moving content function
}
);
});
Not tested but should work theoretically

Related

JQuery backgroundposition only seems to work in one direction

I have been experimenting with Javascript animations for the first time recently and have run into this problem on one of my projects.
The below jquery scrolls horizontally without a problem. However when I add a second value in an attempt to scroll vertically nothing happens, and no errors are thrown up.
$( ".space_background" ).ready(function() {
$( ".space_background" ).animate({
backgroundPosition: "+=200px"
}, 5000, function() {
});
});
The below code is what I thought I would have to add to achieve the effect
$( ".space_background" ).ready(function() {
$( ".space_background" ).animate({
backgroundPosition: "+=200px 200px"
}, 5000, function() {
});
});
I have also tried backgroundPositionX and backgroundPositionY, neither of which work.
Any help sorely appeciated
To move background in vertical direction using jQuery
$( ".space_background" ).ready(function() {
$( ".space_background" ).animate({
backgroundPositionY: "+=200px"
}, 5000, function() {
});
});
Above code works for few browsers reason being jQuery can't animate background position properly as one need it to animate with two values. Above code is working for browsers that implemented the non-standard background-position-x and -y like Internet Explorer. So you need to use any plugins for this like following -
/**
* #author Alexander Farkas
* v. 1.02
*/
(function($) {
$.extend($.fx.step,{
backgroundPosition: function(fx) {
if (fx.state === 0 && typeof fx.end == 'string') {
var start = $.curCSS(fx.elem,'backgroundPosition');
start = toArray(start);
fx.start = [start[0],start[2]];
var end = toArray(fx.end);
fx.end = [end[0],end[2]];
fx.unit = [end[1],end[3]];
}
var nowPosX = [];
nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];
function toArray(strg){
strg = strg.replace(/left|top/g,'0px');
strg = strg.replace(/right|bottom/g,'100%');
strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
}
}
});
})(jQuery);
or
http://snook.ca/technical/jquery-bg/jquery.bgpos.js
Now you can write following code to animate backgrond position using jQuery
$( ".space_background" ).animate({backgroundPosition:"(-150px 0)"});
For more reference:
http://snook.ca/archives/javascript/jquery-bg-image-animations

Why is my function not being called after the DOM is ready?

Can someone explain to me why the rescaleStuff function below is not being invoked on the line where I attempt to invoke it after defining it?
jQuery(function ($) { // $(document).ready equivalent
function scaleStuff()
{
// make elements with class 'same-height-as-width' have the self-explanatory property
$('.same-height-as-width').each(function () {
var thisElement = $(this);
thisElement.height(thisElement.width());
});
// make font size of carousel proportional to height
var factor = 15; // factor to scale the font size, e.g. factor=15 means font-size of the outer div
// if 1/15 of its height. The descendant text elements have font-size defined in em
$('#front-page-carousel-blue-strip').css('font-size', ($('#front-page-carousel-blue-strip').height() / factor).toString() + 'px');
}
scaleStuff(); // scale on page load
// ... bunch of other stuff
}
I shouldn't have to resize the window to get everything to scale immediately after I load the page.
I think you actually wanted:
$(document).ready(function() {
...
})
or
$(function() {
...
})
Note any combination interchanging $ and jQuery is valid.
What you have is fine. You're just missing the closing ) after your declaration:
jQuery(function ($) { // $(document).ready equivalent
function scaleStuff()
{
// make elements with class 'same-height-as-width' have the self-explanatory property
$('.same-height-as-width').each(function () {
var thisElement = $(this);
thisElement.height(thisElement.width());
});
// make font size of carousel proportional to height
var factor = 15; // factor to scale the font size, e.g. factor=15 means font-size of the outer div
// if 1/15 of its height. The descendant text elements have font-size defined in em
$('#front-page-carousel-blue-strip').css('font-size', ($('#front-page-carousel-blue-strip').height() / factor).toString() + 'px');
}
scaleStuff(); // scale on page load
// ... bunch of other stuff
} /* <-- Missing the closing ")". */
Remember the } closes the function being passed as a parameter. The ) closes the jQuery(...) function invocation. Once you add it, it should work fine. I've mocked up an example below using your syntax to show that this indeed works:
jQuery(function ($) {
alert($().jquery);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try using
jQuery(document).ready(function( $ ) { ... });
Take a look here: https://learn.jquery.com/using-jquery-core/document-ready/
$( document ).ready(function() {
console.log( "ready!" );
});
$(function() {
console.log( "ready!" );
});
// Passing a named function instead of an anonymous function.
function readyFn( jQuery ) {
// Code to run when the document is ready.
}
$( document ).ready( readyFn );
// or:
$( window ).load( readyFn );

Simple jQuery Tooltip (position distorted on iPad)

I've used simple jQuery UI tooltip on form-fields of my webpage(viz responsive), its working perfectly on desktop on every browser, but on iPad its get distorted when I tap on form-fields as keypad swipe-up. Also header section of my webpage gets fixed on scroll.
I've used below code for the custom jQuery Tooltip.
$(function () {
$('.form-control').tooltip({
disabled: true,
position: {
my: "left top",
at: "left top-50",
using: function( position, feedback ) {
$( this ).css( position );
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
}).on("focusin", function () {
$(this)
.tooltip("enable")
.tooltip("open");
}).on("focusout", function () {
$(this)
.tooltip("close")
.tooltip("disable");
});
});
I've written this code to re-initialize the tooltip for the focused field by calling its focusin trigger manually when document size changed. It is working as expected on Desktop browsers but on iPad tooltip is being re-initialized at same place again viz incorrect.
var toolTipEl;
$('#inputSuccess, #inputWarning').tooltip({
open: function (event, ui) {
toolTipEl = event.target;
}
});
function checkDocumentHeight(callback){
var lastHeight = document.body.clientHeight, newHeight, timer;
(function run(){
newHeight = document.body.clientHeight;
if( lastHeight != newHeight )
callback();
lastHeight = newHeight;
timer = setTimeout(run, 100);
})();
}
function doSomthing(){
console.log('document resized');
setTimeout(function() {
if ($(toolTipEl).is(':focus')) {
$(toolTipEl).trigger('focusout').trigger('focusin');
}
}, 500);
}
checkDocumentHeight(doSomthing);
Please help me to find out the solution for this.
You will need to reinitialize active Tooltip after completion of any event which cause change in the content (actually height) of your document affecting your Tooltip position.
First keep reference of the element for which the tooltip is active by listening to its events by adding following codes in your tooltip initialization (Keep your existing code as it is. Just add these additional statements).
var toolTipEl = undefined;
$(function () {
$('.form-control').tooltip({
open: function (event, ui) {
toolTipEl = event.target;
}
}).on("focusin", function () {
toolTipEl = undefined;
}).on("focusout", function () {
toolTipEl = undefined;
}).on("mouseleave", function () {
toolTipEl = undefined;
});
});
Please note, as you are displaying tooltip on focusin event as well. So, you will also need to release the variable if you do not want tooltip pop-upped if focus has changed/left.
And then create a function for resetting tooltip like below.
function resetTooltip() {
if (toolTipEl) {
$(toolTipEl).trigger('focusout').trigger('focusin');
};
}
Call this function in any events which is causing change in the document height. For example if content is coming from an ajax request. You can call restTooltip function by listing to the gloab ajax events. See example below.
$( document ).ajaxComplete(function() {
resetTooltip();
});
I hope it will help you. Ask me if you need any further clarification.

jQuery does not apply offset on document.ready

So I am trying to apply a JS function on two events: window.resize and document.ready. The second one just won't work.
When I load the website I want this function to execute and apply the CSS. This is the last JS code before the
I've tried many JS events, but no success.
window.addEventListener("resize", footerMargin);
$( document ).ready(function() { footerMargin(); });
function footerMargin() {
var offset = $( ".section-item--coming-soon").offset();
var novaVar = Math.round(offset.top);
var leftVar = Math.round($( ".footer--section").offset.left);
var heightComingSoon = $( ".section-item--coming-soon").height();
var overall = novaVar + heightComingSoon + 75;
$( ".footer--section").offset({ top: overall, left: leftVar });
}
Upon setting value to leftVar you are using $( ".footer--section").offset.left instead of $( ".footer--section").offset().left.
This Math.round($( ".footer--section").offset.left) will return NaN.
Change that to:
var leftVar = Math.round($( ".footer--section").offset().left);

Why doesn't $(window).animate scrollTop work?

If the following code works (which certainly does)
$( 'html, body' ).animate(
{
"scrollTop": "500"
},
500
);
then why doesn't the following code work?
$( window ).animate(
{
"scrollTop": "500"
},
500
);
If the following code works
$( window ).scroll( myScrollFunctionHandler );
then why doesn't the following code work?
$( 'html, body' ).scroll( myScrollFunctionHandler );
Can somebody please make a comprehensive explanation as to why this has to be this way?
window does not have a scrollTop property, which is why your first example doesn't work. document.body does.
As to your second example, $(window).scroll is the event handler installer for window.onscroll. There is no "body onscroll" event, so obviously an event handler installed on the body (or html) element won't be invoked, as events do not bubble down the DOM, but only up.
This should be due to the internal working of $(window).animate(). Experiment results suggested that inside this jQuery animate() code, $(window).scrollTop() would ALWAYS return zero and $(window).scrollTop(value) could NOT set the value properly.
However, these work before the animate() and in its step callback function. Thus, the code like below would work properly.
function scrollNow(final_val){
var initial_val = $(window).scrollTop(),
diff = final_val - initial_val
;
$(window).animate(
{
scrollTop: diff,
},
{
duration: 1000,
step: function(now, fx){
$(window).scrollTop(initial_val + now);
}
}
);
}

Categories