0

I have the following Javascript code and I'm wondering if I can simplify.

    let seattle = svgDoc.getElementById("Seattle");
    seattle.addEventListener("mouseover", hover);
    seattle.addEventListener("mouseout", unhover);
    seattle.addEventListener("click", select);

    let sanJose = svgDoc.getElementById("San_Jose");
    sanJose.addEventListener("mouseover", hover);
    sanJose.addEventListener("mouseout", unhover);
    sanJose.addEventListener("click", select);

    let losAngeles = svgDoc.getElementById("Los_Angeles");
    losAngeles.addEventListener("mouseover", hover);
    losAngeles.addEventListener("mouseout", unhover);
    losAngeles.addEventListener("click", select);

    more cities...

When user selects a specific city, I need to disable eventlistener ONLY for that specific city and store the city name (which is also the element id).

function select(){
        if(numSelected != 2){
            if(!startSet){start=this.id; startSet = true;}
            else if(!endSet){end=this.id; endSet = true;}
            this.style.fill = "#5cb85c";
            this.removeEventListener("mouseover", hover);
            this.removeEventListener("mouseout", unhover);
            this.removeEventListener("click", select);
            this.addEventListener("click", unselect);
            numSelected++;
        }
    }

I read somewhere I can use JQuery to add event listener to all classes so I can do something like

${".cities"}.addEventListener("click", select);

But is there a way to get the specific element ID and disable only that element's event listener?

1 Answer 1

2

yes. for starters, I think you have a typo over there. It's $(".cities") not ${".cities"} (parentheses instead of curly braces).

Second of all you might notice that what you pass to the $() function is in fact a CSS selector and there are really a lot of these. In the world of CSS if you want to apply a style to an element with a specific class, you use .. If you however want to use a specific ID, you indicate it with #. So If you have an element with ID 'San_Jose', you can reference it with $('#San_Jose')

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.