A
A
Aaang2020-05-07 10:31:36
JavaScript
Aaang, 2020-05-07 10:31:36

How to remove the default action from a link using preventDefault?

By default, the choiceCity link has #, how to remove # when clicked using preventDefault? No matter what # is added to the url.

const choiceCity = document.querySelector(".choice-city");
const modalCity = document.querySelector("#modalCity");
const citiesClose = document.querySelector(".cities-close");
const citiesListItem = document.querySelector(".cities-list-item");
const citiesListItemHref = document.querySelector(".cities-list-item").href;

//Фукция открытия модального окна
function toggleModal(){
  modalCity.classList.toggle("is-open");
}

//Проверка на идентичность урла и адреса ссылки, если похожи - вешаем класс.
if(window.location.href === citiesListItemHref){
  citiesListItem.classList.add("active-city");
}

//Добавляем "слушателя".
choiceCity.addEventListener("click", toggleModal);
citiesClose.addEventListener("click", toggleModal);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Markov, 2020-05-07
@Aaang

function toggleModal(event){
event.preventDefault();
modalCity.classList.toggle("is-open");
}

A
Alexey Ukolov, 2020-05-07
@alexey-m-ukolov

To cancel the default action for an event, you need to execute preventDefault on it. Judging by the question, you know about it. What causes difficulties?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question