What I want to do is have a slider where DIVs move left & right. The code looks as follows:
<script type="text/javascript">
var $slider;
var $transition_time = 1000; // 1 second
var $time_between_slides = 4000; // 4 seconds
$(function() {
$slider = $('.slidemid');
$slider.fadeOut();
// set active classes
$slider.first().addClass('active');
$slider.first().fadeIn($transition_time).css('display', 'inline-block');
// auto scroll
setInterval(function () {
slideright(); }, $transition_time + $time_between_slides );
$('.slidelefta').click(function() {slideleft(); return false;});
$('.sliderighta').click(function() {slideright(); return false;});
});
function slideright() {
$slider = $('.slidemid');
var $i = $slider.find('.active').index();
$slider.eq($i).removeClass('active');
$slider.eq($i).fadeOut($transition_time);
if ($slider.length == $i + 1) $i = -1; // loop to start
$slider.eq($i + 1).fadeIn($transition_time).css('display', 'inline-block');
$slider.eq($i + 1).addClass('active');
}
function slideleft() {
$slider = $('.slidemid');
var $i = $slider.find('.active').index();
$slider.eq($i).removeClass('active');
$slider.eq($i).fadeOut($transition_time);
if ($i == 0) $i = $slider.length; // loop to end
$slider.eq($i - 1).fadeIn($transition_time).css('display', 'inline-block');
$slider.eq($i - 1).addClass('active');
}
</script>
The initial fadeOut, fadeIn and addClass (in the document.ready function) get executed just fine.
The calls to slideright() and slideleft() never get executed though.
Check out this JSBin where i pasted your code and simplified some of the lines since the invocation of the defined functions was the problem. You can see there, in the console, that
in fact the function is being called from the setInterval. Also, i want to point here that it's better to define your functions inside your scope like the way they are declared on the JSBin demo. Why? Well if you define them outside your scope, in the global scope, a very bad person can execute in the console slideright = function () { evilXSShere; } and voilà, your function was overwritten.
Hope it helps.
If you are not getting the any errors on the console, then I think its the issue of javascript scopes. As you are invoking the functions slideright() and sildeleft() inside the functions of anonymous function, but these functions are defined outside the anonymous function within global scope.
Think that anonymous function as a class and you are invoking the function inside the class functions and those function does not belong to that class scope.
Solution(I haven't confirmed the code, the I am pretty sure that should work):
Define those functions inside the anonymous function $(function() or
Wrap those function in the constructor function or object
function slide(){
this.slideRight = function(){}
this.slideLeft = function(){}
}
//invoke it like this
var slider = new Slide();
slider.slideRight//for slideRight
slider.slideLeft// for slideLeft
Related
I have two functions:
function func1(){}
and
function func2(){}
both of these functions requires the following to work
$(document).ready();
$(window).resize();
so I have implemented it to both the functions as follows:
$(document).ready(func1);
$(window).resize(func1);
and
$(document).ready(func2);
$(window).resize(func2);
The problem? there is two;
1) I already have $(function(){ wrapping the above two functions, but I still need need $(document).ready(); why? isn't both the same thing?!
2) I am trying to short-cut the code and only have $(document).ready();"if needed" and $(window).resize(); to appear once and then add functions to it, and not add it to functions. Confused? okay...
so I basically want to do this:
$(document).ready(func1,func2);
$(window).resize(func1,func2);
But it didn't work, any ideas?
My script:
$(function(){
//Prevent clicking on .active & disabled links
'use strict'; $('.active, disabled').click(function(e) {
e.preventDefault();
});
//Off-canvas menu
var $pages = $('#page, #secondHeader'),
$header = $('#header'),
$secondHeader = $('#secondHeader .menu-button');
$secondHeader.on('touchstart click', function(e) {
e.preventDefault();
$pages.toggleClass("pageOpen");
$header.toggleClass("headerOpen");
$(this).toggleClass("menu-button-active");
});
$('#page').on('touchstart click', function() {
$pages.removeClass("pageOpen");
$header.removeClass('headerOpen');
$secondHeader.removeClass("menu-button-active");
});
//Grid system
var gridElement = $(".gridElement", "#grid3");
(function() {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
function GalleryGrid() {
var grid3 = $('#grid3');
var width = $(window).width();
if (width < 1024 && width > 770) {
var grid1 = $('#grid1');
var grid2 = $('#grid2');
for (var i = 0; i < gridElement.length; i++) {
if (i < gridElement.length / 2) {
grid1.append(gridElement[i]);
} else {
grid2.append(gridElement[i]);
}
}
} else {
grid3.append(gridElement);
}
}
$(document).ready(fullScreen);
$(window).resize(fullScreen);
function fullScreen() {
var newHeight = $("html").height() - $("#header").height() + "px";
$(".fullscreen").css("height", newHeight);
}
});
Use a wrapper function to call both functions on the same event:
function go(){
func1(); // Call function 1 and 2.
func2();
}
$(document).ready(go);
$(window).resize(go);
Or, to make absolutely sure the document is ready, you can even attach the resize event listener after the ready event:
$(document).ready(function(){
$(window).resize(go);
});
Do like this.
function fullScreen() {
var newHeight = $("html").height() - $("#header").height() + "px";
$(".fullscreen").css("height", newHeight);
}
fullScreen();
GalleryGrid();
$(window).resize(function(){
fullScreen();
GalleryGrid();
});
Just call the function like fullScreen() no need to use $(document).ready.
For Gallery Grid
Remove from you code. No need to call (function(){}) twice.
(function() {
$(document).ready(GalleryGrid);
$(window).resize(GalleryGrid);
})(jQuery);
I'd suggest using an anonymous function to get this done.
For example:
$(document).ready(function() {
1();
2();
});
That should be a good starting point.
(function(){ ... })();
It is not equivalent to document.ready. Here it is not necessary DOM is ready. It is anonymous function it invoke itself as soon as possible when the browser is interpreting your ecma-/javascript.
Better and suggested to use document.ready():
$(document).ready(function(){
fullScreen();
//other code
});
Don't
Don't call $(document).ready() inside $(document).ready(), it doesn't make sense. The code inside of $(document).ready(/* the code here */) is not executed immediately. It is scheduled for execution sometime later (when the document is ready).
Calling
$(document).ready(function() {
//do this
$(document).ready(some_function)
//do that
});
Is like saying "wait until the document is ready, do this, wait until the document is ready to do some_function, do that."
Document ready event:
$(function(){})
Is just a shortcut/shorthand for:
$(document).ready(function(){})
ready is an event. It belongs to the document object and it is triggered when the document is ready.
To register two functions to be called when the document is ready just do either:
$(document).ready(function() {
func1();
func2();
});
Or
$(function() {
func1();
func2();
});
Or
function func3() {
func1();
func2();
}
$(document).ready(func3);
Or
function func3() {
func1();
func2();
}
$(func3);
Window resize event:
resize is an event. It belongs to the window object and it is triggered when the window is resized.
To register two functions to be called when the window is resized just do:
$(window).resize(function() {
func1();
func2();
});
Or
function func3() {
func1();
func2();
}
$(window).resize(func3);
How come a javascript function like this below...
function stars() {
var mOpacity = $('#area').css('opacity');
if (mOpacity = 1) {
$('#title').find('.stars').animate({"marginTop":"-170px",opacity:1}, 3000)
.animate({opacity: 0}, 400)
.animate({"marginTop":"60px",opacity:0},0, stars);
}
}
stars();
...breaks my browser when I try to do something like this....
$.stars = function() {
var mOpacity = $('#area').css('opacity');
if (mOpacity = 1) {
$('#title').find('.stars').animate({"marginTop":"-170px",opacity:1}, 3000)
.animate({opacity: 0}, 400)
.animate({"marginTop":"60px",opacity:0},0, $.stars());
}
}
$.stars();
What is the lesson here between the 2 styles of functions?
Thanks
Ok based on everyones feedback to see more code, here is a full gimplse of the code on my .js file...
function mIntro() {
/********PRE-GAME ANIMATION*********/
$('#area').css({'opacity':0}).delay(1000).animate({opacity:1},300);
$('#title').find('.age').css({'opacity':0}).delay(2000).animate({opacity:1}, 3000);
function stars() {
var mOpacity = $('#area').css('opacity');
if (mOpacity = 1) {
$('#title').find('.stars').animate({"marginTop":"-170px",opacity:1}, 3000)
.animate({opacity: 0}, 400)
.animate({"marginTop":"60px",opacity:0},0, stars);
}
}
stars();
}
$(function() {
mIntro();
});
I have jquery connected to this .js page and I just can't understand why stars has to be in-cased in a traditional javascript function and not flexibile for a jquery namespace function. I bet it has something to do with the animate tag that re-calls stars, but I am not sure...
Thanks or any advice!!!
You're inadvertently calling it in the second snippet:
.animate(..., $.stars());
You should code it the same way: pass the function, not the result of calling it:
Function: stars $.stars
Result of calling: stars() $.stars()
The difference is that your first example is contained directly within the window object whereas the second example is contained in the jQuery ($) object (note that the $ object is then contained within the window object). As far as why it breaks when you attempt to use the jQuery namespace, I cant say without seeing all of your code, however $ is probably not defined.
I have a problem with my variable scope in a simple slider script that I´ve written (I don't want to use a readymade solution because of low-bandwidth). The slider script is called on statically loaded pages (http) as well as on content loaded through AJAX. On the statically loaded page (so no AJAX) the script seems to work perfect. However when called through AJAX the methods called can't find the elements of the DOM, which halts the necessay animation that is needed for the slider.
All the events are handled through even delegation (using jQuery's on() function), this however provided no solution. I'm quite sure it has something to do with the structure and variable scope of the script, but am unable to determine how to change the structure. So I'm looking for a solution that works in both situations (called normal or through AJAX).
I tried to declare the needed variables in every function, this however resulted in some akward bugs, like the multiplication of the intervals I set for the animation, because of the function scope. Hope somebody can help me in the right direction.
// Slider function
(function (window, undefined) {
var console = window.console || undefined, // Prevent a JSLint complaint
doc = window.document,
Slider = window.Slider = window.Slider || {},
$doc = $(doc),
sliderContainer = doc.getElementById('slider_container'),
$sliderContainer = $(sliderContainer),
$sliderContainerWidth = $sliderContainer.width(),
slider = doc.getElementById('slider'),
$slider = $(slider),
$sliderChildren = $slider.children(),
$slideCount = $sliderChildren.size(),
$sliderWidth = $sliderContainerWidth * $slideCount;
$sliderControl = $(doc.getElementById('slider_control')),
$prevButton = $(doc.getElementById('prev')),
$nextButton = $(doc.getElementById('next')),
speed = 2000,
interval,
intervalSpeed = 5000,
throttle = true,
throttleSpeed = 2000;
if (sliderContainer == null) return; // If slider is not found on page return
// Set widths according to the container and amount of children
Slider.setSliderWidth = function () {
$slider.width($sliderWidth);
$sliderChildren.width($sliderContainerWidth);
};
// Does the animation
Slider.move = function (dir) {
// Makes use of variables such as $sliderContainer, $sliderContainer width, etc.
};
// On ajax call
$doc.on('ajaxComplete', document, function () {
Slider.setSliderWidth();
});
// On doc ready
$(document).ready(function () {
Slider.setSliderWidth();
interval = window.setInterval('Slider.move("right")', intervalSpeed);
});
// Handler for previous button
$doc.on('click', '#prev', function (e) {
e.preventDefault();
Slider.move('left');
});
// Handler for next button
$doc.on('click', '#next', function (e) {
e.preventDefault();
Slider.move('right');
});
// Handler for clearing the interval on hover and showing next and pervious button
$doc.on('hover', '#slider_container', function (e) {
if (e.type === 'mouseenter') {
window.clearInterval(interval);
$sliderControl.children().fadeIn(400);
}
});
// Handler for resuming the interval and fading out the controls
$doc.on('hover', '#slider_control', function (e) {
if (e.type !== 'mouseenter') {
interval = window.setInterval('Slider.move("right")', intervalSpeed);
$sliderControl.children().fadeOut(400);
}
});
})(window);
The HTML example structure:
<div id="slider_control">
<a id="next" href="#next"></a>
<a id="prev" href="#prev"></a>
</div>
<div id="slider_container">
<ul id="slider">
<li style="background-color:#f00;">1</li>
<li style="background-color:#282">2</li>
<li style="background-color:#ff0">3</li>
</ul>
</div>
I notice you have
Slider.setSliderWidth = function() {
$slider.width($sliderWidth);
$sliderChildren.width($sliderContainerWidth);
};
which is called on ajax complete.
Does you ajax update the DOM giving a new DOM element that you could get to by doc.getElementById('slider')? Then your var slider and jquery var $slider are likely pointing to things that no longer exist (even if there is a dom element with slider as the id). To rectify, whenever the ajax is invoked that replaces that element, reinitialize slider and $slider to point to the new jquery wrapped element using the same initialization you have.
slider = doc.getElementById('slider');
$slider = $(slider);
Edit:
I'm not sure where you're going with the variable scope issue, but take a look at this example.
<pre>
<script>
(function(){
var a = "something";
function x (){
a += "else";
}
function y() {
a = "donut";
}
function print (){
document.write(a +"\n");
}
print ();
x();
print ();
y();
print ();
x();
print ();
})();
document.write(typeof(a) + "\n");
</script>
</pre>
It outputs into the pre tag
something
somethingelse
donut
donutelse
undefined
This isn't all that different from what you're already doing. As long as a is not a parameter of a method and is not declared with var in a nested scope, all references to a in code defined within your function(window,undefined){ ...} method will refer to that a, given that a is defined locally by var to that method. Make sense?
To begin, surely you can replace all the getElementById using a jQuery approach. i.e. replace $(doc.getElementById('next')) with $('#next')
I think that when you use on it doesn't search the element for the selector as you are assuming. So you would have to use:
$doc.on('click', '#slider_control #prev',function(e){
e.preventDefault();
Slider.move('left');
});
Wait, what gets loaded through Ajax? The slider-html code? In that case, the Slider has already been 'created' and a lot of your variables will point to nowhere (because these DOM elements did not existed when the variables were initialized). And they will never do so either.
I have this javascript code:
$(function(){
var currentCarouselItem = 1; //set carousel to first slide
var runCarousel = 1;
$(window).load(function(){
setTimeout('autoScroll()', 10000);
});
function autoScroll(num){
if (runCarousel == 1) {
$('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
$(this).removeClass('active');
$(this).attr('style','');
var nextItem = currentCarouselItem + 1;
if (nextItem == 7) {
nextItem = 1;
}
$('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
$(this).addClass('active');
})
})
}
}
})
Whenever I run the site it throws a console error: Uncaught ReferenceError: autoScroll is not defined
Any idea why it thinks it is not defined?
setTimeout('autoScroll()', 10000);
Why put it in quotes?
setTimeout(autoScroll, 10000);
That's for starters.
Additionally, you have scoping issues here.
I could try answering it for you, but I think this guy does a lot better job:
JQuery, setTimeout not working
I think this is because your autoScroll function is inside closure created by outermost $(function(){}). Therefore eval (used to evaluate your string in setTimeout) can't find it, as it runs in a 'global' scope.
You can move the definition of autoScroll outside.
Also, as jcolebrand suggested, remove quotes.
I think it is because when you pass in a string as the first argument for setTimeout() that javascript basically runs eval() from the global scope on that string. autoScroll lives within the scope of $(function() { }) and therefore can't be "seen" from the global scope.
Try changing it to setTimeout(autoScroll, 10000);
There a couple of problems with your code, but the reason that the autoScroll function is not defined is that it defined within the scope of your document ready function, but is executed via eval after the document ready has gone out of scope without the proper closure.
$('.carouselItem.' + currentCarouselItem).animate({left: '975px'}, 'slow', function(){
$(this).removeClass('active');
$(this).attr('style','');
var nextItem = currentCarouselItem + 1;
if (nextItem == 7) {
nextItem = 1;
}
$('.carouselItem.' + nextItem).animate({left: '110px'}, 'slow', function(){
$(this).addClass('active');
});
});
For starters you need a semi colon at the end of functions like this,
How can i call a jQuery function from javascript?
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
});
//just js
function js_fun () {
my_fun(); //== call jquery function
}
Yes you can (this is how I understand the original question).
Here is how I did it. Just tie it into outside context.
For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated
on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
You can't.
function(){
function my_fun(){
/.. some operations ../
}
}
That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.
$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.
Of course, if you want to run this function when the DOM has fully loaded, you should do the following:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
jQuery functions are called just like JavaScript functions.
For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:
$("#orderedlist").addClass("red");
As opposed to a regular line of JavaScript calling a regular function:
var x = document.getElementById("orderedlist");
addClass() is a jQuery function, getElementById() is a JavaScript function.
The dollar sign function makes the jQuery addClass function available.
The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.
In your code
$(function() {
// code to execute when the DOM is ready
});
Is used to specify code to run when the DOM is ready.
It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.
So, to answer your question, just call functions you defined as you normally would.
//create a function
function my_fun(){
// call a jQuery function:
$("#orderedlist").addClass("red");
}
//call the function you defined:
myfun();
I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
<script>
$.myjQuery = function() {
alert("jQuery");
};
$(document).ready(function() {
alert("Welcome!");
});
function display() {
$.myjQuery();
};
</script>
<input type="button" value="submit" onclick=" display();">
Hope this will work for you!