I know that there are many similar questions, but I can't understand what is the mistake in my if statement.
So basically I want to stop clicking nextBtn once I hover over timeoutArea,
but this: timeoutArea.mouseover != true doesn't seems to work.
const timeoutArea = document.getElementById("slider");
var time = 1;
let interval = setInterval(function() {
if (time <= 20 && window.pageYOffset < 393) {
if (timeoutArea.mouseover != true) {
nextBtn.click();
};
time++;
}
else {
time = 1;
}
}, 2000);
if u are using jquery u can use $('#slider').is(':hover') in if statement.
if u use only pure javascript u can use with one function
example fiddle https://jsfiddle.net/9x5hjpk3/
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
so change
if (timeoutArea.mouseover != true) {
nextBtn.click();
};
to
if (!isHover(timeoutArea)) {
nextBtn.click();
};
I was using jquery script like below for hiding and showing a div with a delay in milliseconds:
function slideonlyone(thechosenone) {
$('.newboxes2').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
How can i achieve this result in pure javascript? This is the code i have at the moment:
function showonlyone(thechosenone) {
var newboxes = document.getElementsByTagName("div");
for(var x=0; x<newboxes.length; x++) {
name = newboxes[x].getAttribute("class");
if (name == 'newboxes') {
if (newboxes[x].id == thechosenone) {
newboxes[x].style.display = 'block';
}
else {
newboxes[x].style.display = 'none';
}
}
}
}
The jQuery slideDown effect is not as simple in plain Javascript, but you can set any CSS property with ease.
display: none will make it appear as if box does not exist, and its width and height will be equal to 0. If you want there to be a blank space where the box is, you can use visibility: hidden or opacity: 0. If you use the latter and add the CSS transition: opacity .2s ease to the element, you can make it fade in.
function showOnlyOne(theChosenOne) {
var newBoxes = document.querySelectorAll('div.newboxes');
for (var i = 0, len = newBoxes.length; i < len; ++i) {
var box = newBoxes[i];
if (box.id === theChosenOne) {
box.style.display = 'block';
} else {
box.style.display = 'none';
}
}
}
Problem: In a slide show the fade function below keeps calling the fadein/out functions, please JsFiddle and run for about ten seconds to see problem. Does not work in IE, don't let the jsfiddle run too long it'll probably crash your browser!
JsFiddle: http://jsfiddle.net/HdYmH/
Details (for those interested) : Hi, sorry for posting a question with such a large code chunk. I'm still learning javascript and was trying to figure out how to make a slideshow. I know there are a lot of js slideshows out there but I wanted to figure it out as a learning experience. So be warned there are parts of this code that are very bad. The problem is probably related to the slideshow's changeSlide() method.
I used firebug to find out which method was being called the most apparently after a few seconds fadeOut will be called 20k+ times :|
// Generic fade function that fades in or out
function fade(pElem, pStartOpac, pEndOpac, fps, sec) {
if ((typeof (pElem) !== "string") || (typeof (pStartOpac) !== "number")
|| (typeof (pEndOpac) !== "number") || (typeof (fps) !== "number")
|| (typeof (sec) !== "number")) {
console.log("Parameters incorrect format has to be (string) Element Id, (double) Starting Opacity, (double) End Opacity, (integer) frames per second, (integer) seconds to run");
return;
}
// The CSS opacity property only works from 1 to 0
if (pStartOpac < 0) {
pStartOpace = 0;
}
if (pStartOpac > 1) {
pStartOpac = 1;
}
if (pEndOpac < 0) {
pEndOpac = 0;
}
if (pEndOpac > 1) {
pEndOpac = 1;
}
// Stop the fps from going over 60 or under 1 (The eye will barely notice
// improvements above 60fps and fractional fps are not supported)
if (fps > 60) {
fps = 60;
}
if (fps < 1) {
fps = 1;
}
var totalFrames = (fps * sec);
var opacityChangePerSecond = (Math.abs(pStartOpac - pEndOpac) / sec);
var opacityChangePerFrame = (opacityChangePerSecond / fps);
var timeOutInterval = 1000 * (1 / fps);
// console.log("totalFrames: "+totalFrames);
// console.log("Opacity change per second: " + opacityChangePerSecond);
// console.log("Opacity change per frame: " + opacityChangePerFrame);
// console.log("Time out interval: " + timeOutInterval + " milliseconds");
var opacity = pStartOpac;
var timeoutVar;
var elemId = document.getElementById(pElem);
elemId.style.opacity = opacity;
if (pStartOpac < pEndOpac) {
fadeIn();
return;
} else {
fadeOut();
return;
}
function fadeIn() {
opacity = opacity + opacityChangePerFrame;
if (opacity > pEndOpac) {
clearTimeout(timeoutVar);
return;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeIn, timeOutInterval);
return;
}
function fadeOut() {
if (opacity < pEndOpac) {
clearTimeout(timeoutVar);
return;
}
opacity = opacity - opacityChangePerFrame;
if (opacity < 0) {
opacity = 0;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeOut, timeOutInterval);
return;
}
}
Got the problem: when opacity gets <0 you set it to 0, and then do: if (opacity < pEndOpac). pEndOpac is 0 so, 0<0 evaluates to false and timeout is never cleared. The solution is to do if (opacity <= pEndOpac):
function fadeIn() {
opacity = opacity + opacityChangePerFrame;
if (opacity >= pEndOpac) {
clearTimeout(timeoutVar);
return;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeIn, timeOutInterval);
return;
}
function fadeOut() {
if (opacity <= pEndOpac) {
clearTimeout(timeoutVar);
return;
}
opacity = opacity - opacityChangePerFrame;
if (opacity < 0) {
opacity = 0;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeOut, timeOutInterval);
return;
}
I have this tested function below that works fine for fading an element in or out.
What do I gain by using JQuery?
Thanks
Effects.prototype.fade = function( direction, max_time, element )
{
var elapsed = 0;
function next() {
elapsed += 10;
if (direction === 'up')
{
element.style.opacity = elapsed / max_time;
}
else if (direction === 'down')
{
element.style.opacity = (max_time - elapsed) / max_time;
}
if (elapsed <= max_time) {
setTimeout(next, 10);
}
}
next();
};
Running a search on fadeIn() on the core jquery library I get one hit here:
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
Using the JQuery Source Viewer
function (prop, speed, easing, callback) {
var optall = jQuery.speed(speed, easing, callback);
if (jQuery.isEmptyObject(prop)) {
return this.each(optall.complete, [false]);
}
prop = jQuery.extend({},
prop);
return this[optall.queue === false ? "each" : "queue"](function () {
if (optall.queue === false) {
jQuery._mark(this);
}
var opt = jQuery.extend({},
optall),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, display, e, parts, start, end, unit;
opt.animatedProperties = {};
for (p in prop) {
name = jQuery.camelCase(p);
if (p !== name) {
prop[name] = prop[p];
delete prop[p];
}
val = prop[name];
if (jQuery.isArray(val)) {
opt.animatedProperties[name] = val[1];
val = prop[name] = val[0];
} else {
opt.animatedProperties[name] = opt.specialEasing && opt.specialEasing[name] || opt.easing || "swing";
}
if (val === "hide" && hidden || val === "show" && !hidden) {
return opt.complete.call(this);
}
if (isElement && (name === "height" || name === "width")) {
opt.overflow = [this.style.overflow, this.style.overflowX, this.style.overflowY];
if (jQuery.css(this, "display") === "inline" && jQuery.css(this, "float") === "none") {
if (!jQuery.support.inlineBlockNeedsLayout) {
this.style.display = "inline-block";
} else {
display = defaultDisplay(this.nodeName);
if (display === "inline") {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if (opt.overflow != null) {
this.style.overflow = "hidden";
}
for (p in prop) {
e = new jQuery.fx(this, opt, p);
val = prop[p];
if (rfxtypes.test(val)) {
e[val === "toggle" ? hidden ? "show" : "hide" : val]();
} else {
parts = rfxnum.exec(val);
start = e.cur();
if (parts) {
end = parseFloat(parts[2]);
unit = parts[3] || (jQuery.cssNumber[p] ? "" : "px");
if (unit !== "px") {
jQuery.style(this, p, (end || 1) + unit);
start = (end || 1) / e.cur() * start;
jQuery.style(this, p, start + unit);
}
if (parts[1]) {
end = (parts[1] === "-=" ? -1 : 1) * end + start;
}
e.custom(start, end, unit);
} else {
e.custom(start, val, "");
}
}
}
return true;
});
}
Usually you don't include a library like jQuery just for a single effect, but as a general purpose library in order to simplify things such as DOM manipulation, AJAX calls, setting CSS properties in a way that's cross-browser, in addition to applying effects (such as .fadeIn/.fadeOut) and other applications.
Tipically it's recommended you don't add jQuery for just a simple call. But my reasoning is that you are probably be going to exploit more and more of it's features in the long run, so I don't see a real reason not to use it.
On the subject of implementing your own fadeIn or fadeOut functions, you could look at the jQuery source and extract those methods, or make your own implementation from scratch. But given the fact that jQuery already implemented this method, I don't see why you would want to replicate it, other than for educational purposes.
The biggest reason to use JQuery over your custom code, in my opinion, is that you don't have to maintain the code for multiple browsers and multiple versions. JQuery does a good job of handling the quirks of the major browsers for you.
In addition, there are many other excellent uses for JQuery that you may want to use later.
Concerning the code, when you download JQuery: http://docs.jquery.com/Downloading_jQuery you can get the uncompressed version, which is intended to be readable.
I don't know of a simple way to get only those functions out of JQuery. Why not use the full library?
I'm using the jQuery Rotate plugin, to animate the rotation of an image 90 degrees, and then stop the rotation.
My problem is that it won't stop rotating, even after calling clearInterval();
$(document).ready(function() {
var finalAngle;
var intval = setInterval(function func()
{
$("#myimg").rotate(1);
if(typeof func.angle == 'undefined' )
{
func.angle = 0;
}
func.angle += 1;
finalAngle = func.angle;
}, 1);
if(finalAngle == 90)
{
clearInterval(intval);
}
});
Basically all I'm doing is (statically) counting the angles, and once it hits 90, call the clearInterval function. I had to introduce another variable to store the count so that I could access it outside the setInterval function.
It's easy. setInterval is called then the condition with finalAngle is evaluated and after one milisecond your rotating function is called. Therefore clearInterval is never called when finalAngle is 90.
This code should work for you:
$(document).ready(function() {
var intval = setInterval(function func()
{
$("#myimg").rotate(1);
if(typeof func.angle == 'undefined' )
{
func.angle = 0;
}
func.angle += 1;
if (func.angle == 90)
{
clearInterval(intval);
}
}, 1);
});
The if statement is executed once. Try this?
$(document).ready(function() {
var finalAngle;
var intval = setInterval(function func()
{
$("#myimg").rotate(1);
if(typeof func.angle == 'undefined' )
{
func.angle = 0;
}
func.angle += 1;
finalAngle = func.angle;
if(finalAngle == 90)
{
clearInterval(intval);
}
}, 1);
});
Though I don't see why you can't just get away with...
$(document).ready(function() {
var finalAngle=0;
var intval = setInterval(function func()
{
$("#myimg").rotate(1);
finalAngle++;
if(finalAngle == 90)
{
clearInterval(intval);
}
}, 1);
});