I was looking for a simple JavaScript marquee for a web project of mine and found this one: http://jsfiddle.net/4mTMw/8/
The JavaScript looks like:
var marquee = $('div.marquee');
marquee.each(function() {
var mar = $(this),indent = mar.width();
mar.marquee = function() {
indent--;
mar.css('text-indent',indent);
if (indent < -1 * mar.children('div.marquee-text').width()) {
indent = mar.width();
}
};
mar.data('interval',setInterval(mar.marquee,1000/60));
});
I really like the simplicity of the marquee, but I can't figure out how to make the marquee pause on hover.
If anyone could help point me in the right direction I'd appreciate it!
Thanks,
Josh
create a variable to set animation state.in my code var go.use jquery hover function selector.hover( over, out ). when hover set state variable value to true , when mouse out set it to false. in the animation code do animation only if go variable is true.
marquee.hover(
function() {
go = false;
},
function() {
go = true;
}
);
in animation code
mar.marquee = function() {
if (go) {
demo
http://jsfiddle.net/4mTMw/1333/
Related
In a site I'm building I'm trying to make the navbar change color when I scroll. However, I don't want it to change colors as soon as I start scrolling. I want it at a specified point (once I scroll past my jumbotron).
So far, I've only been able to make it work by scrolling from the top. I'm not quite skilled enough to figure out how to do it past a specific point on my page. I would greatly appreciate some guidance on this.
jQuery script
$(function () {
$(document).scroll(function () {
var $nav = $(".fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
Thanks for any help or guidance!
There are a lot of ways you can do it.
one way could be done with pure javascript.
change changeColorValue that represents the scroll bar value according to your needs.
Here is my suggestion:
LIVE DEMO
JavaScript:
var changeColorValue = 50;
window.addEventListener("scroll", scrollAnim);
function scrollAnim () {
var val = getScrollVal();
if(val > changeColorValue)
{
document.getElementById('mynav').style.backgroundColor = 'red';
}
else
{
document.getElementById('mynav').style.backgroundColor = '#333';
}
}
function getScrollVal()
{
var val = $(document).scrollTop();
return val;
}
I have to make a long animation with jQuery, full of fadeOuts,fadeIns,slideIns,...
The problem I am having is that my code looks ugly and it is full of callback. Also, if I want to stop animation for some time like: slideOut->wait 5 seconds->slideIn I have to use delay and I am not sure if that is the best practice.
Example:
/* Slides */
var slide1 = $('div#slide1'),
slide2 = $('div#slide2'),
slide3 = $('div#slide3');
$(document).ready(function(){
slide1.fadeIn(function(){
slide2.fadeIn(function(){
slide3.fadeIn().delay(3000).fadeOut(function(){
slide2.fadeOut(function(){
slide1.fadeOut();
});
});
});
});
});
JSFIddle: http://jsfiddle.net/ZPvrD/6/
Question: Is there any other way of building animations in jQuery, possibly even some great plugin to help me solve this problem?
Thanks!
Here's the plugin you were looking for :) Does the exact same thing, but is much more flexible than your existing code http://jsfiddle.net/ZPvrD/11/
(function($){
$.fn.fadeInOut = function(middleDelay) {
middleDelay = middleDelay || 0;
var index = 0,
direction = 1, // 1: fading in; -1: fading out
me = this,
size = me.size();
function nextAnimation() {
// Before the first element, we're done
if (index === -1 ) { return; }
var currentEl = $(me.get(index)),
goingForward = direction === 1,
isLastElement = index === (size - 1);
// Change direction for the next animation, don't update index
// since next frame will fade the same element out
if (isLastElement && goingForward) {
direction = -1;
} else {
index += direction;
}
// At the last element, before starting to fade out, add a delay
if ( isLastElement && !goingForward) {
currentEl.delay(middleDelay);
}
if (goingForward) {
currentEl.fadeIn(nextAnimation);
} else {
currentEl.fadeOut(nextAnimation);
}
}
nextAnimation();
return this;
}
})(jQuery);
And you call it like
$('div.slideWrapper>div.slide').fadeInOut(3000);
This process of traversing up and down a list of jQuery elements waiting for each animation to finish could be abstracted so that it could be used for other things besides fadeIn and fadeOut. I'll leave that for you to try out if you feel adventurous.
Try this:
/* Slides */
var slide = $('div[id*="slide"]');
$( function(){
slide.each( function( k ){
$( this ).delay( 500 * k ).fadeIn();
});
});
JQuery animations take two parameters (maximum), duration and complete, duration is the time in milliseconds for how long you want your animation to complete, or you can use "slow" or "fast", and the second params complete which is the callback function.
If don't want to use delay, you may make the previous animation slow.
e.g.
slide1.fadeIn(5000, function(){
slide2.fadeIn();
};
I have been building my own carasol over the past few days.
My Jquery is based on tutorials on the web and also from help and advice from SO.
I am not a Jquery guru just an enthusiast and think my code is a little sloppy, hence the post.
here is a link to the working code: http://jsfiddle.net/JHqBA/2/ (updated link)
basically what happens is:
if someone hits the page with a # values in the url it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two
if someone clicks the numbers it will show the appropriate slide
next and prev also slide through the slides.
The question is, is there anything i could have wrote better as i know there is alot of duplicate code.
I understand its a big ask but it would help me learn a little more (i think my code is a little old school)
if anyone has any questions please feel free to ask and ill answer what it does or is supposed to do.
Sluap
--- Edit ----
I have made only one aniamtion function now which has got rid of alot of duplicate code.
I have yet to look into on function but will do soon.
I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorry
any more tips would be great ill carry on working on this project till i am happy with it.
also is there a better way to write:
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
Jquery full:
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});
Question and answer has been moved over to https://codereview.stackexchange.com/questions/8634/jquery-carasol-build-finished-and-would-like-advice-on-best-practice-neateni/8635#8635
1) Separation of Concerns
Start by refactorring your code in to more granular functions.
You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concerns
Update:
E.g. Instead of having your reel resizing code inline, put it in it's own function, like this:
function setImageReelWidth () {
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
This achieves 2 things:
a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.
b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.
Later, you can also encapsulate the whole thing in it's own "class" (function) and you can move it into it's own js file.
2) The jQuery "on" function
Use the "on" function to attach your click events, rather than the "click" function.
http://api.jquery.com/on/
This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.
3) The ready function
// I like the more succinct:
$(handler)
// Instead of:
$(document).ready(handler)
But you might like the more obvious syntax.
Those are just a few things to start with.
-- Update 1 --
Ok, StackOverflow is not really suited to a refactoring work in progress, but we'll make do. I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.
I would like to know more about the create a new function, outside of
the jQuery ready block as i cant get this working or quite understand
how i can get it to work sorry
I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.
So here is an example of a function defined outside of the ready block, but referenced from within.
function testFunction () {
alert ('it works');
}
$(document).ready(function () {
testFunction();
// ... other code
});
This should pop up an alert box that says, "it works" when the page is loaded.
You can try it for yourself.
Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.
Hello am trying to add a mouse over effect to this code but ive been unsuccessful in doing so, Any help would be great... Am not sure if you will need anymore info but if so I can add anything you need
The problem I have is that when I over over the Tab's I can click the text and it highlights it all :( am after the normal mouse over effect if that can be done
Thanks
<script type="text/javascript">
function init(){
var stretchers = document.getElementsByClassName('box');
var toggles = document.getElementsByClassName('tab');
var myAccordion = new fx.Accordion(
toggles, stretchers, {opacity: false, height: true, duration: 600}
);
//hash functions
var found = false;
toggles.each(function(h3, i){
var div = Element.find(h3, 'nextSibling');
if (window.location.href.indexOf(h3.title) > 0) {
myAccordion.showThisHideOpen(div);
found = true;
}
});
if (!found) myAccordion.showThisHideOpen(stretchers[0]);
}
</script>
To add a mouseover effect in jquery, try it like this:
$('#your id / .your class').bind('mouseover', function() {
alert('hello world');//YOUR CODE HERE
});
I don't see any mouseover events in your code, check the API here:
On Envylabs' site they have a feature where, below the logo, some text keeps changing after a few seconds.
I'm trying to find out what kind of JS/jquery function would do that. Can someone point to a tutorial for this?
You should be using setInterval together with fadeIn and fadeOut to do this. Something like this will work:
var taglines = ['Hello world!', 'Over the rainbow', 'Seeing is believing', 'Bloody hell where am I going?'],
count = 0;
setInterval(function(){
$('#tagline').fadeOut(300, function(){
$(this).text(taglines[(count++)%taglines.length]).fadeIn(300);
})
}, 3000);
See: http://jsfiddle.net/7n9Md/
They use fadeIn/fadeOut together with setTimeout()
You'll find it in http://envylabs.com/javascripts/all.js?1278040567 Line:15
var SubtitleCycle={...}
#samwick : Here is the script that can help you through the point which you are looking for, Try it out!
fadeRecord = function() {
var self = this;
var opacity = 0;
this.recordToEdit.style.opacity = opacity;
var timeInterval = setInterval(
function() {
opacity += 1;
self.recordToEdit.style.opacity = opacity/10;
if(opacity/10 == 1) {
self.recordToEdit = null;
clearInterval(timeInterval);
}
},
100
);
};