Rectangle 27 3

Look at the following JavaScript file. If you scroll down to line 530 you will find the following class:

var Keyboard = new Class(function (constructor) {
    var key = {};

    var eventListener = {
        keyup: {},
        keydown: {},
        keypress: {}
    };

    constructor.overload(["Number"], function (interval) {
        setInterval(keypress, interval);
    });

    window.addEventListener("keyup", keyup, false);
    window.addEventListener("keydown", keydown, false);

    function keyup(event) {
        var keyCode = event.keyCode;
        var listener = eventListener.keyup[keyCode];
        key[keyCode] = false;
        if (listener)
        listener();
    }

    function keydown(event) {
        var keyCode = event.keyCode;
        var listener = eventListener.keydown[keyCode];
        key[keyCode] = true;
        if (listener)
        listener();
    }

    function keypress() {
        for (var code in key) {
            var listener = eventListener.keypress[code];
            if (key[code] && listener) listener();
        }
    }

    this.addEventListener = new Dispatcher(["String", "Number", "Function"], function (type, keyCode, listener) {
        type = eventListener[type];
        if (type) type[keyCode] = listener;
        else throw new Error("Unexpected value for type.");
    });
});

What the author has done is that he has created a special Keyboard class for delegating the key events: keyup, keydown and keypress. The class has only one constructor which accepts a single argument - the interval of the keypress event (which is what you want). You can add event listeners using the addEventListener method of the instance of the Keyboard class:

var keyboard = new Keyboard(125); // fire key press 8 times a second.

keypress.addEventListener("keypress", 65, function () {
    // do something every time A is pressed
});

Note that the above class depends on the following framework: Lambda JS. You can see a working demo of the above script here. Hope this helps.

Your code does not work in Opera. In addition the second event fires after a extra 500 ms delay in Firefox and consecutive events do not maintain the same interval. Plus it can't handle multiple key events at the same time. Let's rectify this problem:

First we need to create a simple script for Delta Timing so that the key events fire after constant interval. We use the following snippet for creating a DeltaTimer:

function DeltaTimer(render, interval) {
    var timeout;
    var lastTime;

    this.start = start;
    this.stop = stop;

    function start() {
        timeout = setTimeout(loop, 0);
        lastTime = Date.now();
        return lastTime;
    }

    function stop() {
        clearTimeout(timeout);
        return lastTime;
    }

    function loop() {
        var thisTime = Date.now();
        var deltaTime = thisTime - lastTime;
        var delay = Math.max(interval - deltaTime, 0);
        timeout = setTimeout(loop, delay);
        lastTime = thisTime + delay;
        render(thisTime);
    }
}

Next we write the logic to fire custom keypressed events. We need custom events since we must be able to handle multiple keys at the same time:

(function (interval) {
    var keyboard = {};

    window.addEventListener("keyup", keyup, false);
    window.addEventListener("keydown", keydown, false);

    function keyup(event) {
        keyboard[event.keyCode].pressed = false;
    }

    function keydown(event) {
        var keyCode = event.keyCode;
        var key = keyboard[keyCode];

        if (key) {
            if (!key.start)
                key.start = key.timer.start();
            key.pressed = true;
        } else {
            var timer = new DeltaTimer(function (time) {
                if (key.pressed) {
                    var event = document.createEvent("Event");
                    event.initEvent("keypressed", true, true);
                    event.time = time - key.start;
                    event.keyCode = keyCode;
                    window.dispatchEvent(event);
                } else {
                    key.start = 0;
                    timer.stop();
                }
            }, interval);

            key = keyboard[keyCode] = {
                pressed: true,
                timer: timer
            };

            key.start = timer.start();
        }
    }
})(1000);

The interval is set at 1000 ms but you may change that. Finally to register an event we do:

window.addEventListener("keypressed", function (event) {
    document.body.innerHTML += event.keyCode + " (" + event.time + " ms)<br/>";
}, false);

This is simple and efficient JavaScript. No jQuery required. You can see the live demo here, and see the difference between your script and mine. Cheers.

Looking at the other question on StackOverflow, this is how you would implement it using the above pattern:

window.addEventListener("keypressed", function (event) {
    switch (event.keyCode) {
    case 37:
        Move(-1, 0);
        break;
    case 38:
        Move(0, -1);
        break;
    case 39:
        Move(1, 0);
        break;
    case 40:
        Move(0, 1);
        break;
    }
}, false);

Using the above code will remove the short delay you're experiencing and also allow multiple events to be fired for different keys at the same time.

Cheers for the idea and info. I've never used Lambda JS before, and I'd rather not have to; but, it is something to fall back on or refer to for ideas on how to write my own.

Very well, @AaditMShah. I will certainly be taking a deeper look at this over the next few days. I greatly appreciate your effort and continued interest.

@MrSlayer - You are welcome. =)

jquery - Is it possible to override the keydown repeat delay, in JavaS...

javascript jquery keypress keydown repeating
Rectangle 27 3

Look at the following JavaScript file. If you scroll down to line 530 you will find the following class:

var Keyboard = new Class(function (constructor) {
    var key = {};

    var eventListener = {
        keyup: {},
        keydown: {},
        keypress: {}
    };

    constructor.overload(["Number"], function (interval) {
        setInterval(keypress, interval);
    });

    window.addEventListener("keyup", keyup, false);
    window.addEventListener("keydown", keydown, false);

    function keyup(event) {
        var keyCode = event.keyCode;
        var listener = eventListener.keyup[keyCode];
        key[keyCode] = false;
        if (listener)
        listener();
    }

    function keydown(event) {
        var keyCode = event.keyCode;
        var listener = eventListener.keydown[keyCode];
        key[keyCode] = true;
        if (listener)
        listener();
    }

    function keypress() {
        for (var code in key) {
            var listener = eventListener.keypress[code];
            if (key[code] && listener) listener();
        }
    }

    this.addEventListener = new Dispatcher(["String", "Number", "Function"], function (type, keyCode, listener) {
        type = eventListener[type];
        if (type) type[keyCode] = listener;
        else throw new Error("Unexpected value for type.");
    });
});

What the author has done is that he has created a special Keyboard class for delegating the key events: keyup, keydown and keypress. The class has only one constructor which accepts a single argument - the interval of the keypress event (which is what you want). You can add event listeners using the addEventListener method of the instance of the Keyboard class:

var keyboard = new Keyboard(125); // fire key press 8 times a second.

keypress.addEventListener("keypress", 65, function () {
    // do something every time A is pressed
});

Note that the above class depends on the following framework: Lambda JS. You can see a working demo of the above script here. Hope this helps.

Your code does not work in Opera. In addition the second event fires after a extra 500 ms delay in Firefox and consecutive events do not maintain the same interval. Plus it can't handle multiple key events at the same time. Let's rectify this problem:

First we need to create a simple script for Delta Timing so that the key events fire after constant interval. We use the following snippet for creating a DeltaTimer:

function DeltaTimer(render, interval) {
    var timeout;
    var lastTime;

    this.start = start;
    this.stop = stop;

    function start() {
        timeout = setTimeout(loop, 0);
        lastTime = Date.now();
        return lastTime;
    }

    function stop() {
        clearTimeout(timeout);
        return lastTime;
    }

    function loop() {
        var thisTime = Date.now();
        var deltaTime = thisTime - lastTime;
        var delay = Math.max(interval - deltaTime, 0);
        timeout = setTimeout(loop, delay);
        lastTime = thisTime + delay;
        render(thisTime);
    }
}

Next we write the logic to fire custom keypressed events. We need custom events since we must be able to handle multiple keys at the same time:

(function (interval) {
    var keyboard = {};

    window.addEventListener("keyup", keyup, false);
    window.addEventListener("keydown", keydown, false);

    function keyup(event) {
        keyboard[event.keyCode].pressed = false;
    }

    function keydown(event) {
        var keyCode = event.keyCode;
        var key = keyboard[keyCode];

        if (key) {
            if (!key.start)
                key.start = key.timer.start();
            key.pressed = true;
        } else {
            var timer = new DeltaTimer(function (time) {
                if (key.pressed) {
                    var event = document.createEvent("Event");
                    event.initEvent("keypressed", true, true);
                    event.time = time - key.start;
                    event.keyCode = keyCode;
                    window.dispatchEvent(event);
                } else {
                    key.start = 0;
                    timer.stop();
                }
            }, interval);

            key = keyboard[keyCode] = {
                pressed: true,
                timer: timer
            };

            key.start = timer.start();
        }
    }
})(1000);

The interval is set at 1000 ms but you may change that. Finally to register an event we do:

window.addEventListener("keypressed", function (event) {
    document.body.innerHTML += event.keyCode + " (" + event.time + " ms)<br/>";
}, false);

This is simple and efficient JavaScript. No jQuery required. You can see the live demo here, and see the difference between your script and mine. Cheers.

Looking at the other question on StackOverflow, this is how you would implement it using the above pattern:

window.addEventListener("keypressed", function (event) {
    switch (event.keyCode) {
    case 37:
        Move(-1, 0);
        break;
    case 38:
        Move(0, -1);
        break;
    case 39:
        Move(1, 0);
        break;
    case 40:
        Move(0, 1);
        break;
    }
}, false);

Using the above code will remove the short delay you're experiencing and also allow multiple events to be fired for different keys at the same time.

Cheers for the idea and info. I've never used Lambda JS before, and I'd rather not have to; but, it is something to fall back on or refer to for ideas on how to write my own.

Very well, @AaditMShah. I will certainly be taking a deeper look at this over the next few days. I greatly appreciate your effort and continued interest.

@MrSlayer - You are welcome. =)

jquery - Is it possible to override the keydown repeat delay, in JavaS...

javascript jquery keypress keydown repeating
Rectangle 27 5

Is this for the whole page or just for certain elements? You could make the scrollbar only appear for certain elements while the mouse is hovering over it.

You could either do it with CSS or JavaScript.

#myElement { overflow: hidden; }
#myElement:hover { overflow: auto; } // Shows relevant scroll bars (vertical/horizontal) if needed
$("#myElement").hover(function(){
    $(this).css("overflow", "auto");
}).hover(function(){
    $(this).css("overflow", "hidden");
});

With the jQuery version you could do more stuff like showing a custom scrollbar or attach the hover event listener to an element that covers the right 100px of the scrolling element so that the scroll bar only appears when the mouse moves to that side. Just a couple of examples.

javascript - CSS or JS make vert scrollbar appear only when scrolling ...

javascript css scrollbar
Rectangle 27 5

Essentially, pull to refresh has only been implemented publicly using a hijacked javascript scrolling mechanisms, like iScroll. This is how Twitter is doing it - with some sort of js webkit css3 scrolling library. But, you'll notice even on an iPhone 4, twitter's scrolling in mobile web is janky and not 100% natural.

Yesterday, I wrote a scroll to refresh handler for overflow: scroll components. Now that iPhone is supporting overflow: scroll, we don't have to hijack the scrolling any longer. This will be especially true when Apple fixes the current iOS -webkit-overflow-scrolling: touch bugs.

I can't yet provide my code open source, but here's the interface to do it, with some comments.

(function(window, $, undefined) {

var hasTouch = 'ontouchstart' in window,
    startEvent = hasTouch ? 'touchstart' : 'mousedown',
    endEvent = hasTouch ? 'touchend' : 'mouseup';

var STATES = {
   ...
};

var CLASS_NAMES = {
   ...
};

var PullToReload = function(callback, wrapper, instructionsContent) {
// create all the dom elements and append the right before a content wrapper, but after a primary main wrapper.
// <div class="mainWrapper" style="overflow: scroll; height: 600px;"><div class="pullToReloadWrapper"></div><div class="contentWrapper"></div></div> is the markup.

// Check if the main wrapper's height is bigger than the content wrapper's height. If so, then change the main wrapper height to be the height of the content wrapper.

// scroll main wrapper by the reload wrapper's height.

// set state to pull

// invoke initEvents()
};

PullToReload.prototype.setState = function(state) {
// set the state of either pull, update, or release. Change CSS classes and content.
}
// boiler plate event handling switch
PullToReload.prototype.handleEvent = function(e) {
    switch (e.type) {
    case startEvent:
        this.start(e);
        break;
    case "scroll": 
        this.scroll(e);
        break;
    case endEvent:
        this.end(e);
        break;
    }
};

PullToReload.prototype.initEvents = function() {
// add event listeners for startEvent and endEvent with method "this"
// calling this in an event listener automatically calls handleEvent()

};

PullToReload.prototype.start = function() {
    // start listening to on scroll for the wrapper
};

PullToReload.prototype.end = function(e) {
// remove scroll event listener
// if the current state is in release, then set state to update and invoke the callback,
// else the state is in pull, then invoke reset()

};

PullToReload.prototype.scroll = function(e) {
// if current scroll position is almost to the top, change state to release.
// else put it back to pull state.

};

PullToReload.prototype.reset = function() {       
// animate scroll to height of reload component. 
// put css classes back to the beginning 
};
})(window, jQuery, I);

This solution works on iOS5, Safari, Chrome, and probably others. I had to use jQuery in a couple places, mainly animating the scroll.

This solution doesn't require a css3 scroll handler, but just overflow: scroll;

html5 - Pull down to refresh on mobile web browser - Stack Overflow

html5 mobile browser pull-to-refresh
Rectangle 27 0

In that case, the question should be closed, not answered.

javascript - JQuery Scroll Listener - Stack Overflow

javascript jquery html css
Rectangle 27 0

$(window).scroll(function(){
  console.log('SCROLL BODY');
});

This should be supported by all browsers.

I know I can on window, but I want to add scroll listener to html tag.

and what different effect do you expect?

I am trying add scroll listener in the html tag level, not to js object like window, but I think I need to change my approach.

javascript - Scroll listener on body - Stack Overflow

javascript jquery scroll listener document-body
Rectangle 27 0

Because the body isn't scrolling, the window is.

In This example, you'll see that the event listener bound to the parent container is what's firing, because that element is the one that's actually scrolling.

<div id="container">
    <p id="content">some text</p>
</div>
#container {
    height: 200px;
    overflow-y: scroll;
}

#content {
    height: 1000px;
}
$('#container').on('scroll', function() {
    console.log('#container');
});

$('#content').on('scroll', function() {
    console.log('#content');
});

So your saying to have scroll on body I would need to set height explicity in css, otherwise the body is constatly expanded and scroll is never there?

Correct - the body doesn't scroll in your case, so a listener bound to it won't work. Bind a listener to the window and you're fine.

I know I can bound listener to window, but I want to add scroll listner to html tag, so in my case windows is not an options, at least if I not gonna change my approach

Scrolling on body is an unusual thing to do. I would change your approach if possible to reduce future headaches. Otherwise, you'll need to add CSS to your body to give you the effect you're looking for.

javascript - Scroll listener on body - Stack Overflow

javascript jquery scroll listener document-body
Rectangle 27 0

There is not a listener for this, but you can have a variable with last position scrolled and check against new one. So it would be something like this:

Keep a variable, say, last_scroll_position, and when you have a scroll, if last_scroll_position - current_position > 0, the user scrolled up, and down if it's less than 0.

<div style='height:10000px;'>

var last_scroll=0;
$(window).scroll(function() {
    var direction='none';
    var current_scroll=$(this).scrollTop();
    if(current_scroll < last_scroll) direction='up';
    else if(current_scroll > last_scroll) direction = 'down';
    last_scroll=current_scroll;
    console.log(direction)
});

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Thanks for answering my question. The logic behind this seems simple enough, the only problem I am having is capturing the value for <code>last_scroll_position</code>. I have a function that captures <code>scrollTop</code> so creating the variable for the current scroll position is pretty easy. Just can't wrap my head around how to capture the previous scroll position.

jquery - Is there a javascript event listener that detects only when t...

javascript jquery events
Rectangle 27 0

Ok, I added a bit of JavaScript that listens to the first time the document is scrolled down. When the document is scrolled down for the first time, it'll force itself back to the top, then it'll remove the listener so that the user may scroll as desired afterward.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="style.css"></link>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>

<body>
<iframe src="http://store4549118.ecwid.com/#!/~/cart" width="100%" height="100%" id="Container"></iframe>
<script src="scripts.js"></script>
</body>
</html>

JAVASCRIPT (In a file named scripts.js)

window.addEventListener("scroll", runOnScroll);

function runOnScroll(){
    $('html,body').animate({scrollTop: 0},1000);
    window.removeEventListener("scroll", runOnScroll);
}

Give it a shot, and let me know if it works!

I've updated the question. thanks, it does work but take a look at the question, there is one little thing left to see @marcodelvalle

To animate the scroll, it's easiest to use the JQuery library, so I added two lines of code to the answer above: First: <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> in the <head> to import the JQuery library. Second: changed the scroll to $('html,body').animate({scrollTop: 0},1000); this is a JQuery command that tells the page to animate to the top in 1000 milliseconds.

javascript - stop parent page from scrolling down to iframe - Stack Ov...

javascript jquery html css iframe
Rectangle 27 0

You need to add an event listener using JavaScript, means when a particular element comes to view port an event is fired and it fetches the data from some external resources. The data comes in JSON and you need to extract it and append the info in a DIV. For this I have made a script which fetches the data from Google Docs using Jquery and the event is fired after you scroll to the bottom most portion. You can check the infinite scroll here

How do you make an infinite scroll page in Blogger? - Stack Overflow

blogger infinite-scroll
Rectangle 27 0

Without anyone to pull me out of the newbie abyss, I floundered until I go something. This answer looked so close to what I needed that I used it as a starting point. Now I've at least gotten here.

The key is, as I suspected, creating a timer to call the function again if the mouse is still down and clearing it on mouseup:

var _this = null;
    $('.jcarousel-next').mousedown(function () {
        $('.jcarousel-next').jcarouselControl({
              target: '+=2'
        });
        _this = $(this);
        _this.click();
        window.setTimeout(CallAgain, 100);
    });

    $('.jcarousel-next').mouseup(function () {
            _this = null;
        });

    function CallAgain() {
        if (_this != null) {
            //alert("Inside Call again");
            _this.click();
            window.setTimeout(CallAgain, 100);
        }
    };

On the fiddle, the right arrow has the scroll on mousedown, while left/prev is left at the default. Now I just have to smooth it out.

For posterity's sake: to smooth out the scrolling, I used jQuery(document).ready(function () { $('.jcarousel').jcarousel({ wrap: 'circular', 'animation': { 'duration': 1500, 'easing': 'linear' } });

javascript - jQuery scroll on mousedown with listener (for jCarousel) ...

javascript jquery jcarousel