Html сделать неактивной ссылку

I have an anchor link that I want to disable once the user clicks on it. Or, remove the anchor tag from around the text, but definitely keep the text.

I can do this easily with a button by adding .attr(«disabled», «disabled»);
I successfully added the disabled property, but the link was still clickable.
I don’t really care if the text is underlined or not. Any clue? When you click on the wrong musician, it should just add «Wrong» and then become unclickable.
When you click and you are correct, it should add «Awesome» and then disable all tags.

remove the href part and add to your CSS : «cursor:pointer», I assume you have a $(‘#ThisLink’).click or something like that?

19 Answers 19

The cleanest method would be to add a class with pointer-events:none when you want to disable a click. It would function like a normal label.

Using this idea a even easier way would be to use a[disabled] as selector for the css so you would not require to add the .disableClick class to the anchor

this solution is good for me in modern browsers. i have usable anchor tags that are bound to click events, and to discourage spamming them as their processes do their thing i programmatically add this and then remove it when the process is done. tabbing to a disabled anchor tag in my case isnt a concern either, but may be for others. YMMV

Читайте также:  What is php file inclusion

Pairing this with tabindex=»-1″ appears to satisfy all the use cases except for a click event being generated in JavaScript.

Please explain your solution so that future visitors to this question will understand how it solves the problem at hand.

Use pointer-events CSS style. (as Jason MacDonald suggested)

Simple adding «disabled» attribute to anchor will do the job if you have global CSS rule like following:

+1 for adding the styling through the [disabled] attribute rather than a class. It should be noted that pointer-events: none; doesn’t work in anything older than IE11 though.

All IEs has its own proprietary logic of disabling anchor, buttons and even other elements by default.This workaround needed for non-IE browsers.

+1. Just so I don’t have to look it up again next time: required javascript (using jQuery) would be $(«#elementid»).attr(«disabled», «disabled»); . Also may be helpful to include cursor: default in the CSS (as suggested by Muhammad Nasir).

I just realized what you were asking for(I hope). Here’s an ugly solution

var preventClick = false; $('#ThisLink').click(function(e) < $(this) .css('cursor', 'default') .css('text-decoration', 'none') if (!preventClick) < $(this).html($(this).html() + ' lalala'); >preventClick = true; return false; >); 

This could actually really solve the problem, sort of. Instead of .click, use .on on the body and delegate to ‘a[disabled]’. Then put the css code in the actual css using the same selector. Then, preventing click is as simple as event.preventDefault() and return false

Removing the a via the removeAttr doesn’t work for me. .removeAttr(«href») awesomealbums.info/?WhoAmI

Bootstrap provide us with .disabled class. Please use it.

But .disabled class only works when the ‘a’ tag already has class ‘btn’. It doesn’ t work on any old ‘a’ tag. The btn class may not be appropriate in some context as it has style connotations. Under the covers, the .disabled class sets pointer-events to none , so you can make CSS to do the same thing as Saroj Aryal and Vitrilo have sugested. (Thank you, Les Nightingill for this advice).

the .disabled class only works when the ‘a’ tag already has class ‘btn’. It doesn’ t work on any old ‘a’ tag. The ‘btn’ class may not be appropriate in some context as it has style connotations. Under the covers, the .disabled class sets pointer-events to none, so you can make css to do the same thing as Saroj Aryal and Vitrilo have sugested.

Thank you for your detailed comment. It clarifies a lot for many users. May I use some text from your comment to extend my answer?

$("#ThisLink").addClass("disable_a_href"); 

The best way is to prevent the default action. In the case of anchor tag, the default behavior is redirecting to href specified address.

So following javascript works best in the situation:

You could use the onclick event to disable the click action:

Or you could just use something other than an tag.

You can combine this with text-decoration: none and .disabledLink < color: #000 !important; >to make it appear like regular text.

Just remove the href attribute from the anchor tag.

Jason MacDonald comments worked for me, tested in Chrome, Mozila and IE.

Added gray color to show disable effect.

Jquery was selecting only first element in the anchor list, added meta character (*) to select and disable all element with id #ThisLink .

$("#ThisLink*").addClass("disable_a_href"); 

Write this a single line of jQuery Code

$('.hyperlink').css('pointer-events','none'); 

if you want to write in css file

Create following class in style sheet :

Add this class to you link dynamically as follow.

 some text // or using jquery  

This is the method I used to disable.Hope it helps.

$("#ThisLink").attr("href","javascript:;"); 

what is the anchor holds styling rules that are essential to their program, this is a fix that disregards css

Although this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.

Never trust the browser because the user can change the page in any way without the server’s knowledge.

If a link is to work only once, the first thing you need to do is make sure that server side the click is accepted only once (with an onetime token specified as querystring for example), because the URL present in the href attribute can be copied by the user and inserted in the navigation bar of the browser and runned multiple times.

On the javascript side, the safest thing you can do is completely replace the link with another tag, preserving the content:

/** Replace element, preserving attributes and moving descendant nodes from the previous one. * * @param element Element to be replaced changing tag. * @param new_tag New element tag. * @return New created element. */ function rename_element_tag(element, new_tag) < let new_block = document.createElement(new_tag); for (let j = 0; j < element.attributes.length; ++j) new_block.setAttribute(element.attributes[j].name, element.attributes[j].value); $(new_block).insertAfter(element); while (element.childNodes.length >0) new_block.appendChild(element.childNodes[0]); $(element).remove(); return new_block; > 

This function replaces the passed element in place by «modifying» the tag, and preserves attributes and content by iterating all child nodes via vanilla javascript instead of jQuery to handle text nodes as well.

In your case you must skip the href attribute.

Источник

Как сделать ссылку неактивной после нажатия?

Есть ссылка, при нажатии на которую нужно вывести блок информации и одновременно сделать ссылку неактивной (чтобы ее не было видно). Первый пункт я сделал, а сделать ссылку неактивной не выходит.

e.preventdefault() есть такая штука которая делает ссылку кликабельной, но не активной, или через сss pointer-events: none;/* делаем ссылку некликабельной */

Если я правильно вас понял, вам нужно задать оформление для ссылок псевдокласса :visited — htmlbook.ru/css/visited

2 ответа 2

document.getElementById('additional').addEventListener('click', function(e) < e.preventDefault(); e.target.style.display = 'none'; var info = document.getElementById('additional-info'); if (info.style.display === 'none') < info.style.display = 'block'; >else < info.style.display = 'none'; >>, false);

Спасибо! Здесь это работает! Но что то в моем коде — не хочет. Пробовал в коде прописать — и подключать внешний скрипт 🙁

можете в JSBin ili JSFiddle скинуть весь код страницы? может id такая же есть еще одна или что-то в этом роде..

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.26.43546

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Is there some CSS property or something that I can use with my anchor tag so as to make it unclickable or I HAVE to do stuff in code behind to get what I want? [edit] onclick=return false; is refreshing the page.. I dont want that.. want this anchor tag to appear as a plain text.. actually I have css applied on anchor tag.. so cant change it to simple lable or whatever

You can’t trust what’s going on client side. So you have to deny access to the link on the server either way.

I want it as a link only..just don’t want it to clickable..I set its property «Disabled=true» in code behind..didnt work

12 Answers 12

The pointer-events CSS property can be set in modern browsers on a particular graphic element and tells under what circumstances the element can become the target of pointer events.

The none value makes sure that the element is never the target of pointer events and prevents all click, state and cursor options on the element.

However, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases. — MDN

Cursor style may differ based on pointer-events value on parent or its descendant elements. Unless you set cursor explicitly.

If you want the anchor tag to be a link destination, but not a link source then omit the href attribute and only have a name attribute. The HTML 4.01 spec allows this and suggests that browsers display the text within the href-less anchor tag as normal text.

Remember not to use just a but a:link and a:visited for your real links. The same applies to :hover : use a:link:hover and a:visited:hover instead of just a:hover .

including an onclick=»return false» attribute on the anchor element does the trick. While this solution uses javascript and not css

Note that won’t work if Javascript is disabled. Also «Open Link in New Tab» will still work and web crawlers will still follow this link. So I don’t think it’s an ideal solution.

in the anchor tag, I believe — that’s what I do on csharpindepth.com, anyway. I wouldn’t like to swear to how widely supported it is, admittedly — you probably want to check that. Seems okay on Chrome, IE and Firefox though. I don’t know if there’s an equivalent just in CSS.

Note that I believe this will make the link visibly unclickable (however the browser wants to do that) rather than just not do anything.

EDIT: I’ve just tried this on a local file, and it doesn’t work. whereas it definitely works on csharpindepth.com. Worth trying then, but also probably worth looking at other approaches 🙂

EDIT: As BoltClock notes, this isn’t strictly valid HTML — which may mean it will only work in quirks mode, for example. (That could explain my failure to produce it locally.)

You’re probably better off with a JavaScript solution along with a CSS style to change the link appearance. but I’ll leave this answer here just for the record.

Источник

Как сделать ссылку некликабельной с помощью CSS

Когда вы создаете веб-страницу, иногда может возникнуть необходимость отключить ссылку на определенном элементе. В этой статье мы расскажем, как сделать ссылку некликабельной с помощью CSS.

Использование CSS свойства pointer-events

Самый простой способ сделать ссылку некликабельной — это использование CSS свойства pointer-events. Данный способ позволяет отключить кликабельность элемента, но не удаляет ссылку. Вот пример кода:

Здесь мы создаем класс «disabled» для ссылки, которую хотим сделать некликабельной, и задаем ему свойство pointer-events со значением «none».

Использование CSS свойства text-decoration

Еще один способ сделать ссылку некликабельной — это убрать ее стандартное оформление. Для этого мы можем использовать CSS свойство text-decoration. Вот пример кода:

Здесь мы задаем класс «disabled» для ссылки и устанавливаем ему значение text-decoration: none, которое убирает подчеркивание ссылки. Мы также устанавливаем свойство cursor: default, чтобы курсор не менял свой вид при наведении на некликабельную ссылку.

Использование атрибута href

Еще один способ сделать ссылку некликабельной — это удалить ее атрибут href. Это приведет к тому, что при нажатии на ссылку ничего не произойдет. Вот пример кода:

Здесь мы добавляем класс «disabled» для ссылки и удаляем атрибут href, задав его значение «#». Это сделает ссылку некликабельной.

В заключение, существует несколько способов сделать ссылку некликабельной с помощью CSS. Выбор зависит от того, что вы хотите добиться и как вы хотите, чтобы ваша страница выглядела.

Источник

Оцените статью