Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Mapbox / Javascript: Implementing hover and clicked state

I'm trying to allow my Mapbox zones to have both clicked and hover states. Once something has been clicked I want that to persist, stay in that state, even if I then hover on another tile.

In implementing it though, what happens is when I click it turns to the clicked state, but moving my mouse on that area or another tile changes it from clicked back to hover.

Here is a demo of this: https://codepen.io/hiven/pen/zYPbRNK

The key bit of code is here:

     if (hoveredStateId !== null) {
        map.setFeatureState(
           { source: "states", id: hoveredStateId },
           { mystate: null }
        );
     }
     if (hoveredStateId !== 2) {
     hoveredStateId = e.features[0].id;
     map.setFeatureState(
        { source: "states", id: hoveredStateId },
        { mystate: 1 }
     );
     }

The state 1 is hover, state 2 is clicked. With this code I thought it would only set the state to hover if the tile is not at clicked state (2) already. However this doesn't seem to work, as moving your mouse on a clicked tile changes it to hover state.

Where have I gone wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You didn't include quite enough code above. The key bit of code is actually this:

map.on('mousemove', 'state-fills', (e) => {
              if (e.features.length > 0) {
                  if (hoveredStateId !== null) {
                      map.setFeatureState({
                          source: "states",
                          id: hoveredStateId
                      }, {
                          mystate: null
                      });
                  }

It says: when the mouse moves over anything, clear the current state.

Also, this is clearly wrong:

     if (hoveredStateId !== 2) {

You seem to have confused the state (null, 1 or 2) with the id of the feature (any number 0 or greater).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!