Here is excerpt from my larger JavaScript file:
function dashboardConfig()
{
$(window).on('resize', function () {
var viewport = {
width : $(this).width(),
height : $(this).height()
};
el.siteContainer.css(
{
marginTop : (viewport.height - 652) / 2
});
el.dashboardSlide.css(
{
marginLeft : (viewport.width - 1024) / 2,
marginRight : (viewport.width - 1024) / 2
});
//Calculate how many nav elements
el.navElements.each(function(i)
{
el.dashboard.css(
{
width : viewport.width * (i + 1)
});
$(this).click(function()
{
//HERE IS THE VARIABLE I WOULD LIKE TO USE
var dashboardSlidePosition = viewport.width * i;
el.navElements.removeClass('active');
$(this).addClass('active');
el.dashboard.animate(
{
left : -dashboardSlidePosition
},500, function()
{
el.dashboard.css(
{
left : -dashboardSlidePosition
});
});
});
});
//I WANT TO PERFORM ANOTHER FUNCTION HERE AND HAVE IT USE THE VALUE OF dashboardSlidePosition
}).trigger('resize');
}
I want to know how I can pass the value of the variable, dashboardSlidePosition, to another function. Please can anyone explain how?
Many thanks in advance.
You can declare it at the outer edge of your scope. Make sure to give it an initial value so that you don't try to use it before it has been set properly.
function dashboardConfig()
{
var dashboardSlidePosition = null;
function anotherFunction() {
if (dashboardSlidePosition != null) {
// ...
}
}
$(this).click(function()
{
dashboardSlidePosition = viewport.width * i;
}
}
Put it into the proper scope:
function dashboardConfig()
{
var dashboardSlidePosition = 0;
Next, remove var when redefining it.
Now you can use it because it's in the scope of the function.
Related
I want to execute an exeternal function inside the JQuery method. The problem appear when I try to call the method, the one looks undefined. How could I solve this? I amb using Typescript with Angular 2
ngAfterViewInit() {
jQuery(".mo-table").scroll(function () {
var trueDiveHeight = jQuery(".mo-table")[0].scrollHeight;
var divHeight = jQuery(".mo-table").height();
var scrollLeft = trueDiveHeight - divHeight;
if (jQuery(".mo-table").scrollTop() >= scrollLeft - 150) {
this.onSearch();
console.log("new bottom")
}
});
}
The method onSearch is an external function, and is Undefined.
onSearch(): void {
this.updateTableReport(this.scrollId, this.buildParams())
}
Any help would be appreciated.
Change
jQuery(".mo-table").scroll(function () {
to
jQuery(".mo-table").scroll( ()=> {
your this is not refering to your component
or the old js way:
ngAfterViewInit() {
var self = this; //<-- assign this to self here
jQuery(".mo-table").scroll(function () {
var trueDiveHeight = jQuery(".mo-table")[0].scrollHeight;
var divHeight = jQuery(".mo-table").height();
var scrollLeft = trueDiveHeight - divHeight;
if (jQuery(".mo-table").scrollTop() >= scrollLeft - 150) {
self.onSearch(); //<-- use self here
console.log("new bottom")
}
});
}
I am working on a slider, here is the code for it:
$(document).ready(function() {
// MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH
var totalWidth = 0;
$('.slide').each(function() {
totalWidth = totalWidth + $(this).outerWidth(true);
});
var maxScrollPosition = totalWidth - $(".slider_wrap").outerWidth();
function slideMove($targetSlide) {
if ($targetSlide.length) {
var newPosition = $targetSlide.position().left;
if (newPosition <= maxScrollPosition ) {
$targetSlide.addClass('slide--active');
$targetSlide.siblings().removeClass("slide--active");
$(".slider").animate({
left : - newPosition
});
}
else {
$(".slider").animate({
left : - maxScrollPosition
});
};
};
};
$(".slide").width(totalWidth);
$(".slide:first").addClass("slide--active");
$(".next_post").click(function(){
var $targetItem = $(".slide--active").prev();
slideMove('.slide');
});
$(".prev_post").click(function(){
var $targetItem = $(".slide--active").next();
slideMove('.slide');
});
});
While I would expect this to work, I am getting an error that says: TypeError: $targetSlide.position is undefined. From the if statement in the function slideMove. Why doesn't this work? I am still learning jQuery so sorry if it is an obvious answer.
change this
slideMove('.slide');
to this
slideMove($('.slide'));
In your method slideMove you are expecting a JQUERY DOM ELEMENT where as you are giving it just a STRING which is class name of that particular DOM element
YO! you change it to this
...
$('.next_post').click(function(){
var $targetItem = $('.slide--active').prev();
slideMove($('.slide'));
});
$('.prev_post').click(function(){
var $targetItem = $('.slide--active').next();
slideMove($('.slide'));
});
...
I'm trying to make this function working multiple times:
Currently works only with the h1 tag
how can I make it working for the <div class="logo"> as well? I don't want to repeat the function, I need a way to make the function working for various elements.
demo: http://jsfiddle.net/33Ec8/4/
JS:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
}
(function fadeInDiv() {
var divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: 0.3
});
});
Your question isn't stated very clearly, so I would strongly suggest describing what the code should do vs what it does.
That said, here is a half-blind attempt at answering what I think you want.
You could pass in the selector as a parameter to displayThese.
function displayThese(selectorString)
{
var $elementsUnderWhichNothingShouldFade = $(selectorString);
...
}
then when you call displayThese, you can pass in any complex selector you like.
var divsToChange = displayThese('h1, div.logo')
Of course, you would need to add extra logic to test whether the image elements were underneath any of the resulting $elementsUnderWhichNothingShouldFade (which is a list of elements).
I'm trying to have a bunch of variables reset themselves on a resize (I'm just a little crazy like that. Yes, I know virtually no one will do it as their using the page). I want to be able to have the plugin that I created (hScroll) reset it's variables when the user resizes the page. I only want to declare them and set them within one line, so I tried using the window.variableName = ... but that didn't seem to work. Once again, all I want to be able to do is have to declare and set the variable within one line, and on resize, have the variables reestablish themselves, since a few are size dependent. As you can see, I have also tried the triggerHandler method as well, but it does not seem to be working.
(function($) {
$.fn.extend({
hScroll: function(options) {
var defaults = {
container: "nav",
sliderName: ".sliderName",
partContainer: ".beep"
};
var o = $.extend(defaults, options);
return this.each(function() {
// I want to set global variables and have them reset... START
var slider = $(o.container + " " + o.sliderName),
sliderWidth = slider.outerWidth(),
container = $(o.container),
containerWidth = container.outerWidth(),
containerInnerWidth = containerWidth - (2 * parseInt(container.css("padding-left"))),
sliderPieces = slider.children(o.partContainer),
numberOfPieces = sliderPieces.length,
containerWidth = $(o.container).width(),
piecesWidth = 0;
// set slide widths
if (containerInnerWidth > sliderWidth / numberOfPieces) {
piecesWidth = sliderWidth / numberOfPieces
} else {
piecesWidth = containerInnerWidth;
}
sliderPieces.width(piecesWidth);
// set gutter and how many pieces can be seen at once.
var wholePiecesSeen = Math.floor(containerInnerWidth / piecesWidth),
gutter = parseInt((containerInnerWidth - (wholePiecesSeen * piecesWidth)) / 2);
// END - I want this block to be reset when the window is resized.
var isContainerBigEnough = function() {
if (containerInnerWidth > sliderWidth) {
$(o.container).removeClass("tooBig");
} else {
$(o.container).addClass("tooBig");
}
}
isContainerBigEnough();
// arrow variables
$(o.container + " .previous").click(function() {
var addOn = 0,
newPosition = 0,
thisFarGone = parseInt(slider.css("left")),
moveThisFar = piecesWidth,
allTheWay = containerInnerWidth - sliderWidth;
// always make sure to center your tiles
if (thisFarGone == allTheWay) {
moveThisFar = moveThisFar - gutter;
console.log(moveThisFar);
console.log("in");
};
newPosition = -thisFarGone - moveThisFar;
//make sure it doesn't go too far
if (newPosition < 0) {
newPosition = 0;
}
newPosition = parseInt(newPosition); // - addOn);
slider.css({
"left": (-newPosition) + "px"
});
});
$(o.container + " .next").click(function() {
var addOn = 0,
newPosition = 0,
thisFarGone = parseInt(slider.css("left")),
moveThisFar = piecesWidth;
// always make sure to center your tiles
if (thisFarGone == 0 ||
thisFarGone == -0 ||
thisFarGone == undefined) {
moveThisFar = moveThisFar - gutter;
};
newPosition = moveThisFar - thisFarGone;
//make sure it doesn't go too far
if (newPosition > sliderWidth - containerInnerWidth) {
newPosition = sliderWidth - containerInnerWidth;
}
newPosition = parseInt(newPosition); // - addOn);
slider.css({
"left": (-newPosition) + "px"
});
});
$(window).resize(function() {
console.log("working");
$(o.container).triggerHandler("hScroll");
});
});
}
});
})(jQuery);
$(document).ready(function() {
$(".posts-timeline").hScroll({
container: ".posts-timeline",
sliderName: "#slider",
partContainer: ".post"
});
});
Something like this?
console.log("working");
$(o.container).hScroll("hScroll");
Maybe not exactly that, but if you want those variables to be reassigned, I'm guessing that would wind up being done somewhere in $(window).resize(function() {
I'm using a jquery plugin on my page, vTicker, "for easy and simple vertical news automatic scrolling". I'm using it in combination with an rss jquery plugin. It's working fine, but I need to create a button that will do a manual scroll. Can anyone tell me how to do this? I'm guessing I need to call the moveUp function from the vTicker file, but because of the way the function is created, as well as how the vticker itself is created, I'm not really sure how to do it.
I create my vTicker like this:
$('#ticker1').rssfeed(uRL).ajaxStop(function() {
$('#ticker1 div.rssBody').vTicker();
})
And here is the vTicker code:
/*
* Tadas Juozapaitis ( kasp3rito#gmail.com )
*/
(function($){
$.fn.vTicker = function(options) {
var defaults = {
speed: 700,
pause: 15000,
showItems: 3,
animation: '',
mousePause: true,
isPaused: false
};
var options = $.extend(defaults, options);
moveUp = function(obj2, height){
if(options.isPaused)
return;
var obj = obj2.children('ul');
var iframe = $('#iFrame2');
first = obj.children('li:first').clone(true);
second = obj.children('li:odd:first').clone(true);
iframe.attr('src', (second.children('h4').children('a').attr("href")));
obj.animate({top: '-=' + height + 'px'}, options.speed, function() {
$(this).children('li:first').remove();
$(this).css('top', '0px');
});
if(options.animation == 'fade')
{
obj.children('li:first').fadeOut(options.speed);
obj.children('li:last').hide().fadeIn(options.speed);
}
first.appendTo(obj);
};
return this.each(function() {
var obj = $(this);
var maxHeight = 0;
obj.css({overflow: 'hidden', position: 'relative'})
.children('ul').css({position: 'absolute', margin: 0, padding: 0})
.children('li').css({margin: 0, padding: 0});
obj.children('ul').children('li').each(function(){
if($(this).height() > maxHeight)
{
maxHeight = $(this).height();
}
});
obj.children('ul').children('li').each(function(){
$(this).height(maxHeight);
});
obj.height(maxHeight * options.showItems);
var interval = setInterval(function(){ moveUp(obj, maxHeight); }, options.pause);
if(options.mousePause)
{
obj.bind("mouseenter",function(){
options.isPaused = true;
}).bind("mouseleave",function(){
options.isPaused = false;
});
}
});
};
})(jQuery);
Thanks for reading.
The short answer is, you can't. The moveUp function is totally isolated within the scope of the plugin, and you cannot call it directly.
To modify the plugin so that you can manually scroll, add this just before the line return this.each(function() {:
$.fn.extend({
vTickerMoveUp: function() {
var obj = $(this);
var maxHeight = 0;
obj.children('ul').children('li').each(function(){
if($(this).height() > maxHeight) maxHeight = $(this).height();
});
moveUp(obj, maxHeight);
}
});
Then, to scroll, do this:
var ticker = $('#ticker1 div.rssBody').vTicker();
ticker.vTickerMoveUp();
Since the moveup declaration is missing a var that means moveup() would be statically defined as a property of window (ie, global) once vTicker has been called. And thus I would think you could call moveup() from anywhere after that.