Dominic Nguyen
Dominic Nguyen

Reputation: 71

Add CSS change on touch start for mobile devices

I'm attempting to change the CSS of a link before the app navigates to another page. I've previously added an ontouchstart event to the link element to greatly speed up navigation in the app. The problem is that the event fires and app navigates before the CSS can change.

What are some ways I could provide user feedback before the page changes?

Additional notes:

Here is some example code:

HTML

<a class="button" ontouchstart="goTo('#!/stats', 'buttonActive', this);" onclick="goTo('#!/stats', 'buttonActive', this);">STATS</a>

CSS

.button {
    display: flex;
    background-color: #000000; 
    color: dodgerblue;
    font-size: 4vmin;
    cursor: pointer;
    text-decoration: none;
    font-size: 7vmin;
    border: 0.75vmin solid dodgerblue;
    border-radius: 1vmin;
    height: 8vh;
    width: 40vmin;
    padding: 2vmin;
    margin: 5vmin auto;
    align-items: center;
    justify-content: center;
}
.buttonActive {
    background-color: dodgerblue;
    color: white;
}

JS

function goTo (location, addClass, elem) {
    elem.className += addClass;
    window.location.href = location;
}

Upvotes: 2

Views: 1578

Answers (2)

Dominic Nguyen
Dominic Nguyen

Reputation: 71

I ended up using ontouchend instead of ontouchstart. This allowed for the CSS to change while the user's finger is pushed down and the page will not navigate until the user releases his/her finger.

Upvotes: 1

Gray Spectrum
Gray Spectrum

Reputation: 733

You could probably just add a slight delay to the goTo function's window.location.href call. This would give the css time to update before the new file is requested. It might look something like this:

function goTo (location, addClass, elem) {
  elem.className += addClass;
  setTimeout(function(){ 
    window.location.href = location;
  }, 250);
}

That would make for a 250-millisecond delay...likely enough time to allow the css to update and your viewers to recognize the change before the new file request is initiated.

Upvotes: 0

Related Questions