javascript - Vanilla JS: delay click event to add animation - Stack Overflow

No jQuery please!I would love not to use jQuery for this, because it's a big library and I only ne

No jQuery please!

I would love not to use jQuery for this, because it's a big library and I only need to do this single thing:

I would like to add a short delay to a click event so I can fade elements off my page using CSS.

I could post all of the code I've tried so far, but you'd get bored. So here's the one that I think is the closest:

document.getElementsByTagName('a').onclick = function (e) {

// Delay setting the location for one second
setTimeout(function() {this.href}, 90000);

var animOut = document.getElementByClassName('animateOut');
   animOut.className += 'out';
};

I've already ruled out using onbeforeunload, so hijacking the click event seems to be the best way.

Once again, I know this would be a doddle in jQuery, but I would like to avoid it if it's possible.

Thanks so much for your answers.

Ben


UPDATE

Thanks to menters guest271314 and The Alpha, I've settled on this approach, but still have yet to plete the puzzle.

window.onload = function(){

var links = document.getElementsByTagName('a');
for( var i=0,il = links.length; i< il; i ++ ){
 links[i].onclick = clickHandler;
}

function clickHandler(event) {

event.preventDefault();

// Delay setting the location for one second
setTimeout(function() {

  location.href = this.href;
}, 90000);

// add `s` to `Element`
var animOut = document.getElementsByClassName("animateOut");

// iterate `animOut` elements
for (var i = 0; i < animOut.length; i++) {
   // add `out` `className` to `animOut` element at index `i`
   animOut[i].classList.add("out");
};
};
};

Having to iterate over the a tags was an addition I have learned from reading other posts (I'll link to them in a minute).

Unfortunately, the setTimeout function doesn't seem to be working. I need to refine what's in this function, but don't know in what way.

Further assistance would be most wele.

Thanks

Ben

No jQuery please!

I would love not to use jQuery for this, because it's a big library and I only need to do this single thing:

I would like to add a short delay to a click event so I can fade elements off my page using CSS.

I could post all of the code I've tried so far, but you'd get bored. So here's the one that I think is the closest:

document.getElementsByTagName('a').onclick = function (e) {

// Delay setting the location for one second
setTimeout(function() {this.href}, 90000);

var animOut = document.getElementByClassName('animateOut');
   animOut.className += 'out';
};

I've already ruled out using onbeforeunload, so hijacking the click event seems to be the best way.

Once again, I know this would be a doddle in jQuery, but I would like to avoid it if it's possible.

Thanks so much for your answers.

Ben


UPDATE

Thanks to menters guest271314 and The Alpha, I've settled on this approach, but still have yet to plete the puzzle.

window.onload = function(){

var links = document.getElementsByTagName('a');
for( var i=0,il = links.length; i< il; i ++ ){
 links[i].onclick = clickHandler;
}

function clickHandler(event) {

event.preventDefault();

// Delay setting the location for one second
setTimeout(function() {

  location.href = this.href;
}, 90000);

// add `s` to `Element`
var animOut = document.getElementsByClassName("animateOut");

// iterate `animOut` elements
for (var i = 0; i < animOut.length; i++) {
   // add `out` `className` to `animOut` element at index `i`
   animOut[i].classList.add("out");
};
};
};

Having to iterate over the a tags was an addition I have learned from reading other posts (I'll link to them in a minute).

Unfortunately, the setTimeout function doesn't seem to be working. I need to refine what's in this function, but don't know in what way.

Further assistance would be most wele.

Thanks

Ben

Share Improve this question edited Mar 21, 2016 at 14:59 endymion1818 asked Mar 21, 2016 at 7:37 endymion1818endymion1818 4854 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

I can't really take credit for this, the 2 users below (guest271314 and The Alpha) deserve a lot of recognition for what they helped me to achieve. The full code, with a couple of refinements, is:

window.onload = function(){

var links = document.getElementsByTagName('a');

for( var i=0,il = links.length; i< il; i ++ ){
links[i].onclick = clickHandler;
}

function clickHandler(event) {

event.preventDefault();

var travelTo = this.getAttribute("href");

// add `s` to `Element`
var animOut = document.getElementsByClassName("animateOut");

// iterate `animOut` elements
for (var i = 0; i < animOut.length; i++) {
   // add `out` `className` to `animOut` element at index `i`
   animOut[i].classList.add("out");
};

// Delay page out until the animation finishes
setTimeout(function() {
  window.location.href = travelTo;
}, 1000);
};
};

You may try something like this:

document.getElementsByTagName('a').onclick = function (event) {
    event.preventDefault();
    document.getElementByClassName('animateOut').className += ' out';
    setTimeout(function() {
        location.href = this.href;
    }, 1000);
};

There should be an "s" at document.getElementsByClassName . To add className to all animateOut elements can use a for loop; change this.href to window.location.href = e.target.href if expected result is to navigate to href of clicked a element; else leave as this.href is requirement is to refresh current window.location.href : this.href within setTimeout

document.getElementsByTagName("a").onclick = function (e) {

// Delay setting the location for one second
setTimeout(function() {window.location.href = this.href}, 90000);

// add `s` to `Element`
var animOut = document.getElementsByClassName("animateOut");
// iterate `animOut` elements
for (var i = 0; i < animOut.length; i++) {
   // add `out` `className` to `animOut` element at index `i`
   animOut[i].classList.add("out");
};

Eight (08) years late to the party but here is what you need to do to introduce the delay anywhere in plain JavaScript.

This is the syntax:

setTimeout(() => { /*your fancy stuff here*/ }, DelayYouWantInMs);

For example, I want to show the "Loading..." for 2 seconds on my page to draw a dynamic HTML table when a button is clicked which further retrieves the data from an api.

Below is how you use above syntax:

    setTimeout(() => {
        fetch('https://jsonplaceholder.typicode./users')
            .then(response => response.json())
            .then(createTable)
            .catch(error => console.error(error));

    }, 2000);

And a full blown working example:

<!DOCTYPE html>
<html>
<body>
    <h2>Build table from API response</h2>
    <button id="foo">Lets do it !</button>
</body>
<script>
    const button = document.querySelector('#foo');
    button.addEventListener('click', fetchData, false);

    function fetchData() {
        button.textContent = 'Loading...Please wait...';
        button.disabled = true;
        
        setTimeout(() => {
            fetch('https://jsonplaceholder.typicode./users')
                .then(response => response.json())
                .then(createTable)
                .catch(error => console.error(error));

        }, 2000);
    }
    function getColumnHeadings(data) {
        return Object.keys(data[0]).map(key => {
            return `<td>${key}</td>`;
        }).join('');
    }
    function getRows(data) {
        return data.map(obj => {
            return `<tr>${getCells(obj)}</tr>`
        }).join('');
    }
    function getCells(obj) {
        return Object.values(obj).map(value => {
            return `<td>${value}</td>`;
        }).join('');
    }
    function createTable(data) {
        const headings = getColumnHeadings(data);
        const rows = getRows(data);
        const html = `<table><tbody><tr class="headings">${headings}</tr>${rows}</tbody></table>`
        document.body.insertAdjacentHTML('beforeend', html);
        button.remove();
    }
</script>
</html>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742362129a4429595.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信