JQuery => How to make the code a library [duplicate] - javascript

This question already has answers here:
How to write a simple jQuery plugin [closed]
(3 answers)
Closed 5 years ago.
I am finally finished with what I've started. I created a responsive lightbox slideshow!
But, I am kinda facing a problem. I want to make it a library...In other words, I want the code to apply to the html classes that I can add infinitely (Like all libraries do).
Thank you!
var imageSliding = $('.box > .img');
$('.lightbox').click(function() {
$('.backdrop, .box').animate({
'opacity': '.50'
}, 300, 'linear');
$('.box').animate({
'opacity': '1.00'
}, 300, 'linear');
$('.backdrop, .box').css('display', 'block');
});
$('.close').click(function() {
close_box();
});
$('.backdrop').click(function() {
close_box();
});
function close_box() {
$('.backdrop, .box').animate({
'opacity': '0'
}, 300, 'linear', function() {
$('.backdrop, .box').css('display', 'none');
});
}
/* Slider */
var speed = 100;
$(".prev").click(function() {
var gallery = $(this).closest('.box').find("ul.gallery"),
now = gallery.children(":visible"),
last = gallery.children(":last"),
prev = now.prev();
prev = prev.index() == -1 ? last : prev;
now.fadeOut(speed, function() {
prev.fadeIn(speed);
});
});
$(".next").click(function() {
var gallery = $(this).closest('.box').find("ul.gallery"),
now = gallery.children(":visible"),
first = gallery.children(":first"),
next = now.next();
next = next.index() == -1 ? first : next;
now.fadeOut(speed, function() {
next.fadeIn(speed);
});
});
$(".gallery li").click(function() {
var first = $(this).parent().children(':first'),
next = $(this).next();
next = next.index() == -1 ? first : next;
$(this).fadeOut(speed, function() {
next.fadeIn(speed);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

See jQuery main Documentation for this: basic-plugin-creation
Also TeamTreehouse has a good tutorial About this: writing-your-own-jquery-plugins

Related

Slide Div Across Page using JQuery/CSS

I have used the following code which makes it every time you click on the div it will animate and move across the page, thus moving the next one across after it.
http://jsfiddle.net/jtbowden/ykbgT/2/
However, I am trying to make it so it automatically scrolls every 3 seconds without having to click. I have tried the following adjustments to the javascript using a timer but it seems to just spazz out and not scroll correctly:
<script>
$('.box').click(function () {
$(this).animate({
left: '-50%'
}, 500, function () {
$(this).css('left', '150%');
$(this).appendTo('#container');
});
$(this).next().animate({
left: '50%'
}, 500);
});
$(document).ready(function ()
{
setInterval(function ()
{
$('.box').click();
console.log("BOX CLICKED.");
}, 3000);
});
</script>
Does anyone have any ideas?
Thanks
Similar to Zack's answer(but simpler, IMHO), I've found that the following works for you
id = 1
setInterval(function(){
$('#box' + id).animate({
left: '-50%'
}, 500, function() {
$(this).css('left', '150%');
$(this).appendTo('#container');
});
$('#box' + id).next().animate({
left: '50%'
}, 500);
id = id <= 5 ? id + 1 : 1;
},4000)
Sorted it by using the following adjustments:
<script>
ActiveDashboards = {};
ActiveDashboards["Projects"] = true;
ActiveDashboards["SHEQs"] = false;
ActiveDashboards["HR"] = false;
function ShowNextDashboard()
{
if (ActiveDashboards["Projects"] == true)
{
//Hide this one.
$('#box1').animate({
left: '-50%'
}, 500, function () {
$('#box1').css('left', '150%');
$('#box1').appendTo('#container');
});
//Show SHEQs one.
$('#box2').animate({
left: '50%'
}, 500);
ActiveDashboards["Projects"] = false;
ActiveDashboards["SHEQs"] = true;
}
else if (ActiveDashboards["SHEQs"] == true)
{
//Hide this one.
$('#box2').animate({
left: '-50%'
}, 500, function () {
$('#box2').css('left', '150%');
$('#box2').appendTo('#container');
});
//Show HR one.
$('#box3').animate({
left: '50%'
}, 500);
ActiveDashboards["SHEQs"] = false;
ActiveDashboards["HR"] = true;
}
else if (ActiveDashboards["HR"] == true)
{
//Hide this one.
$('#box3').animate({
left: '-50%'
}, 500, function () {
$('#box3').css('left', '150%');
$('#box3').appendTo('#container');
});
//Show Projects one.
$('#box1').animate({
left: '50%'
}, 500);
ActiveDashboards["HR"] = false;
ActiveDashboards["Projects"] = true;
}
}
$(document).ready(function ()
{
setInterval(function ()
{
ShowNextDashboard();
}, 4000);
});
</script>
Probably a better way of doing it, but it's working fine and scrolling through each one.

Infinite move object on mouseover

I'm trying to create a feature where when you mouseover an object, another object begins to move continuously until you mouseout. For some reason in my code it stops after the first 10 pixels, which is this,
http://jsfiddle.net/JoshuaWaheed/7df29/
$("a").mouseover(function(){
$("div").animate({
"margin-left": "+=" + 10 + "px"
});
});
How can I make it run continuously, while on mouseover only?
Try to do a clever recursion here,
$("a").mouseover(function () {
stop = false;
animate()
});
$("a").mouseout(function () {
stop = true;
$("div").stop();
});
function animate() {
if (stop) { return; }
$("div").animate({
"margin-left": "+=" + 10 + "px"
}, animate);
}
DEMO
Don't use .animate, because it's not designed for this. You can move it yourself by altering the CSS in a setInterval loop:
$("a").mouseover(function () {
// store the interval ID on the DOM element itself
$(this).data('tc', setInterval(function () {
$("div").css({
"margin-left": "+=1"
});
}, 20) // milliseconds
);
});
$("a").mouseout(function () {
// clear the interval ID
clearInterval($(this).data('tc'));
});
http://jsfiddle.net/mblase75/5QJTT/
Try if this works :
var over = false;
$("a").mouseover(function(){
over = true;
while(over == true)
{
$("div").animate({
"margin-left": "+=" + 10 + "px"
});
}
});
$("a").mouseout(function(){
over = false;
});

Is it possible to cancel hover event based on condition while still hovering?

I need to make my hover event, which executes a function, to stop running that function based on the condition of margin-top.
Here is my fiddle - http://jsfiddle.net/Joe_Foster/LwrVv/
$(document).ready(function(){
function moveUp(){
$('#a').animate({
"margin-top" : "-=" + 30},200, "linear", moveUp);
};
/* $('.up').hover(function(){
if ($m =='0px'){
alert('stop');
}
else{
moveUp();
}
});
*/
$('.up').hover(function(){
moveUp();
},
function(){
$('#a').stop();
});
//---------------------------------------
function moveDown(){
$('#a').animate({
"margin-top" : "+=" + 30},200, "linear", moveDown);
};
$('.down').hover(function(){
moveDown();
},
function(){
$('#a').stop();
});
});
Please help me before I burst more blood vessels in my eyes :)
Thank you.
I was just looking at your JS Fiddle and while I'm not certain of what values you wished to stop at, here is the code I used to make it work:
JS:
var upperThreshold = -607;
var lowerThreshold = 0;
function moveUp()
{
if ($("#a").css("marginTop").replace(/px/,'') <= upperThreshold)
{
console.log($("#a").css("marginTop"));
$('#a').stop();
return false;
}
else
{
$('#a').animate({"margin-top" : "-=" + 30},200, "linear", moveUp);
}
}
function moveDown()
{
if ($("#a").css("marginTop").replace(/px/,'') >= lowerThreshold)
{
console.log($("#a").css("marginTop"));
$('#a').stop();
return false;
}
else
{
$('#a').animate({"margin-top" : "+=" + 30},200, "linear", moveDown);
}
}
$(document).ready(function()
{
$('.down').hover(function()
{
moveDown();
},
function()
{
$('#a').stop();
}
);
$('.up').hover(function()
{
moveUp();
},
function()
{
$('#a').stop();
}
);
});
JSFiddle: http://jsfiddle.net/irishgeek82/ePdE5/
Please let me know if this works for you! :)

jQuery animate one another another

Im trying to animate one elment after another, but I have some troubles with this
$.getJSON('http://localhost/json/example/json.json', function(data){
var ele = jsonElements(data);
for(var i = 1; i <= ele; i++)
{
$('#test').append('');
$('#t_'+i).animate({
'top': data['t_'+i]['top'],
'left': data['t_'+i]['left']
}, 800).delay(1000);
}
});
It works, but all elements have animation in same time, any advice how to make it one after another?
$.getJSON('http://localhost/json/example/json.json', function(data){
var ele = jsonElements(data);
one_by_one(ele,1);
});
function one_by_one(ele,i){
if(i > ele)
return;
$('#test').append('');
$('#t_'+i).animate({
'top': data['t_'+i]['top'],
'left': data['t_'+i]['left']
}, 1000, function() {
// Animation complete
one_by_one(ele,i+1);
});
}
call one_by_one(i);
I added an example on http://jsfiddle.net/VS8tQ/64/

Autoplay for javascript moving boxes

Please go to : http://gati.simptome-remedii.ro/ . As you can see there is a carousel effect in the header and it goes forward and backwards once you click on the arrows or press left/right key .
I need it to autoplay so I need an autosliding effect.
Time interval should be 5 seconds ( I guess I can set that up later ) .
This carousel effect uses jquery-1.3.1.min.js and slider.js .
Slider.js
$(function() {
var totalPanels = $(".scrollContainer").children().size();
var regWidth = $(".panel").css("width");
var regImgWidth = $(".panel img").css("width");
var regTitleSize = $(".panel h2").css("font-size");
var regParSize = $(".panel p").css("font-size");
var movingDistance = 300;
var curWidth = 350;
var curImgWidth = 220;
var curTitleSize = "15px";
var curParSize = "15px";
var $panels = $('#slider .scrollContainer > div');
var $container = $('#slider .scrollContainer');
$panels.css({'float' : 'left','position' : 'relative'});
$("#slider").data("currentlyMoving", false);
$container
.css('width', ($panels[0].offsetWidth * $panels.length) + 100 )
.css('left', "-350px");
var scroll = $('#slider .scroll').css('overflow', 'hidden');
function returnToNormal(element) {
$(element)
.animate({ width: regWidth })
.find("img")
.animate({ width: regImgWidth })
.end()
.find("h2")
.animate({ fontSize: regTitleSize })
.end()
.find("p")
.animate({ fontSize: regParSize });
};
function growBigger(element) {
$(element)
.animate({ width: curWidth })
.find("img")
.animate({ width: curImgWidth })
.end()
.find("h2")
.animate({ fontSize: curTitleSize })
.end()
.find("p")
.animate({ fontSize: curParSize });
}
//direction true = right, false = left
function change(direction) {
//if not at the first or last panel
if((direction && !(curPanel < totalPanels)) || (!direction && (curPanel <= 1))) { return false; }
//if not currently moving
if (($("#slider").data("currentlyMoving") == false)) {
$("#slider").data("currentlyMoving", true);
var next = direction ? curPanel + 1 : curPanel - 1;
var leftValue = $(".scrollContainer").css("left");
var movement = direction ? parseFloat(leftValue, 10) - movingDistance : parseFloat(leftValue, 10) + movingDistance;
$(".scrollContainer")
.stop()
.animate({
"left": movement
}, function() {
$("#slider").data("currentlyMoving", false);
});
returnToNormal("#panel_"+curPanel);
growBigger("#panel_"+next);
curPanel = next;
//remove all previous bound functions
$("#panel_"+(curPanel+1)).unbind();
//go forward
$("#panel_"+(curPanel+1)).click(function(){ change(true); });
//remove all previous bound functions
$("#panel_"+(curPanel-1)).unbind();
//go back
$("#panel_"+(curPanel-1)).click(function(){ change(false); });
//remove all previous bound functions
$("#panel_"+curPanel).unbind();
}
}
// Set up "Current" panel and next and prev
growBigger("#panel_3");
var curPanel = 3;
$("#panel_"+(curPanel+1)).click(function(){ change(true); });
$("#panel_"+(curPanel-1)).click(function(){ change(false); });
//when the left/right arrows are clicked
$(".right").click(function(){ change(true); });
$(".left").click(function(){ change(false); });
$(window).keydown(function(event){
switch (event.keyCode) {
case 13: //enter
$(".right").click();
break;
case 32: //space
$(".right").click();
break;
case 37: //left arrow
$(".left").click();
break;
case 39: //right arrow
$(".right").click();
break;
}
});
}
);
I am really looking forward to receiving an answer.
Thank you !
Regards,
Razvan.
The simple thing would be to do
setInterval( function() {$('.right').click();}, 5000 );
This will call click the right button every 5 seconds..
But you will need to add some logic if you want it to go both left and right ..
update
Try this (put it right before the $(window).keydown line ..)
setInterval( function(){
if (curPanel == totalPanels)
{
curPanel = 1;
$("#slider").data("currentlyMoving", true);
$(".scrollContainer")
.stop()
.animate({
"left": movingDistance
}, function() {
$("#slider").data("currentlyMoving", false);
});
returnToNormal("#panel_"+totalPanels);
growBigger("#panel_1");
}
else
{
$('.right').click();
}
} ,5000 );

Categories