I would like to move the href assignment to CSS.
Something like <a style="href: url('Home.htm');">Home</a> instead of Home.
Is it possible to do this in CSS?
I have a button at several places in my site whose corresponding URL value, might change in the future. I want to change the target address only in one place, i.e. my CSS file, instead of having to manually change them for every instance of that button.
This behaviour isn't really supported, as explained in other answers. But if you really need this on a page, it's possible to add it using some JavaScript. Used-defined custom variables/properties in CSS need to start with --, and I'll use the name --href-override.
We'll listen for all mousedown and touchstart events on links in the document. These events are useful because they'll always occur before the click is registered. Each time we handle one of these events, we check if the associated link has a --href-override property/variable defined in CSS. If so, we replace the HTML href with the CSS --href-override value, and the browser will automatically use that new value when handling the click event.
function overrideEventTargetHref(event) {
// if it's the beginning of a click on a link...
if (event.target.tagName === 'A') {
var link = event.target;
var override = getComputedStyle(link).getPropertyValue('--href-override').trim();
// if the link has an CSS href-override and it's different than the HTML href...
if (override && override != link.href) {
// replace the HTML href with the CSS href-override
link.href = override;
}
}
}
window.addEventListener('mousedown', overrideEventTargetHref, false);
window.addEventListener('touchstart', overrideEventTargetHref, false);
.override {
--href-override: https://stacksnippets.net/;
}
actually example.com
secretly stacksnippets.net
This also work properly for things like middle-clicking to open in a new tab.
This is quite a hack and you usually wouldn't want to do it. But if your situation requires it, you can.
CSS is a styling sheet, so the short answer is no. Also not entirely sure as to what your reason for wanting to is, but if it's due to changing data, use JavaScript or PHP to do this instead. Much easier, logical, and possible.
The href property stands for hypertext reference. It is not an entity that lends itself to styling; see this resource. If you wish to style how that location's text value appears on a page, you could write code that styles the a tag and if you want to get fancier you could add on a pair of span tags, as follows:
CSS:
a {
font: 14px Arial,Helvetica;
color: #00c;
text-decoration:none;
border: 4px dotted #009;
}
a:hover {
border: 3px solid #009;
}
span {
color: #f0f;
}
<span>Home</span>
As for changing the values of the buttons, if you run Linux, it provides various helpful utilities, such grep; see this discussion. Also, see this article.
Related
I'm trying to make a custom cursor setter. You can customize cursors in CSS, so I went there first.
html {
cursor: url(MY URL GOES HERE), auto !important;
}
It works at this point. However, I want the average user to be able to enter an image URL and see the cursor change to that. I decided to use JavaScript to do that.
function customCursor() {
var v1 = prompt("Enter the image URL you want to be your mouse cursor.");
var style = document.createElement('style');
style.innerHTML = `html {cursor:url(` + v1 + `); } `;
document.head.appendChild(style);
}
However, it doesn't work. I checked the current page HTML with Firebug, and the tag is added. And when I use JavaScript to add it manually, it works. So why would it not work?
I also made sure to keep the images I chose below 128x128.
After massive changes to the code, it still is not working. However, I now understand a reason why (by using devtools to read what was actually being added):
Instead of dynamically using my variable, it was treating the variable name as the URL itself. This makes this question mostly irrelevant.
I'm creating a log in form and I am doing hide/show states in JavaScript.
Is there a way that when I load the page, the first button is on active state, while when I click anoother button it becomes active and the previous one is no longer active?
My HTML:
<a class="login-button" >login</a><a class="login-button">register</a><a class="login-button">cant login?</a>
My CSS:
.login-button
{color:#00BFFF;
padding-right:20px;
}
.login-button:active
{ color:#FFF;
font-family:customfont-bold;
}
You could just use JavaScript as #Sachin point out, or do it in pure CSS making use of the :target pseudoclass.
The only thing you should do is to add a hyperlink reference (href) to your anchor tag, which, I think, would make your markup more semantic.
HTML
login
CSS
#login:target {
color:#FFF;
font-family:customfont-bold;
}
Since you taget your question just as css/html I thought a CSS solution would be nice.
You can use Javascript or Jquery to achieve this. Here is sample for you
$("a").click(function() {
$("a").removeClass("active");
$(this).addClass("active");
});
CSS
.active
{
color:#FFF;
font-weight:bold;
}
of-course you can use selector more specifically.
Just rename the class that u want to appear active at first to class="login-button active"
Then insert a javascript function to change from one to another, for example:
function{
var element = document.getElementsByClassName("login-button active");
element.className="login-button";
}
You could also add some id="" in order to make easier the changes. Then u can use:
var element = document.getElementById("yourID");
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.
<a href='' id='ThisLink'>some text</a>
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 <a> tags.
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.
.disableClick{
pointer-events: none;
}
<a href='javascript:void(0);'>some text</a>
Use pointer-events CSS style. (as Jason MacDonald suggested)
See MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events.
Its supported in most browsers.
Simple adding "disabled" attribute to anchor will do the job if you have global CSS rule like following:
a[disabled], a[disabled]:hover {
pointer-events: none;
color: #e1e1e1;
}
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;
});
$('a').removeAttr('href')
or
$('a').click(function(){ return false})
It depends on situation
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).
Add a css class:
.disable_a_href{
pointer-events: none;
}
Add this jquery:
$("#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:
$('#ThisLink').click(function(e)
{
e.preventDefault();
});
You could use the onclick event to disable the click action:
<a href='' id='ThisLink' onclick='return false'>some text</a>
Or you could just use something other than an <a> tag.
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.
.disable_a_href{
pointer-events: none;
**color:#c0c0c0 !important;**
}
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
.hyperlink{
pointer-events: none;
}
Create following class in style sheet :
.ThisLink{
pointer-events: none;
cursor: default;
}
Add this class to you link dynamically as follow.
<a href='' id='elemID'>some text</a>
// or using jquery
<script>
$('#elemID').addClass('ThisLink');
</script>
This is the method I used to disable.Hope it helps.
$("#ThisLink").attr("href","javascript:;");
Try this:
$('a').contents().unwrap();
Simply in SASS:
.some_class{
// styles...
&.active {
pointer-events:none;
}
}
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 <a> link with another tag, preserving the content:
/** Replace element, preserving attributes and moving descendant nodes from the previous one.
*
* #param {HTMLElement} element Element to be replaced changing tag.
* #param {String} new_tag New element tag.
* #return {HTMLElement} 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.
$('#ThisLink').one('click',function(){
$(this).bind('click',function(){
return false;
});
});
This would be another way to do this, the handler with return false, which will disable the link, will be added after one click.
The easyest way
In your html:
<a id="foo" disabled="true">xxxxx<a>
In your js:
$('#foo').attr("disabled", false);
If you use it as attribute works perfectly
If I create an HTML anchor tag and set the disabled attribute to true, I get different behaviors in different browsers (surprise! surprise!).
I created a fiddle to demonstrate.
In IE9, the link is grayed out and does not transfer to the HREF location.
In Chrome/FF/Safari, the link is the normal color and will transfer to the HREF location.
What should the correct behavior be? Is IE9 rendering this incorrectly and I should implement some CSS and javascript to fix it; or is Chrome/FF/Safari not correct and will eventually catch up?
Thanks in advance.
IE appears to be acting incorrectly in this instance.
See the HTML5 spec
The IDL attribute disabled only applies to style sheet links. When the
link element defines a style sheet link, then the disabled attribute
behaves as defined for the alternative style sheets DOM. For all other
link elements it always return false and does nothing on setting.
http://dev.w3.org/html5/spec/Overview.html#the-link-element
The HTML4 spec doesn't even mention disabled
http://www.w3.org/TR/html401/struct/links.html#h-12.2
EDIT
I think the only way to get this effect cross-browser is js/css as follows:
#link{
text-decoration:none;
color: #ccc;
}
js
$('#link').click(function(e){
e.preventDefault();
});
Example: http://jsfiddle.net/jasongennaro/QGWcn/
I had to fix this behavior in a site with a lot of anchors that were being enabled/disabled with this attribute according to other conditions, etc. Maybe not ideal, but in a situation like that, if you prefer not to fix each anchor's code individually, this will do the trick for all the anchors:
$('a').each(function () {
$(this).click(function (e) {
if ($(this).attr('disabled')) {
e.preventDefault();
e.stopImmediatePropagation();
}
});
var events = $._data ? $._data(this, 'events') : $(this).data('events');
events.click.splice(0, 0, events.click.pop());
});
And:
a[disabled] {
color: gray;
text-decoration: none;
}
disabled is an attribute that only applies to input elements per the standards. IE may support it on a, but you'll want to use CSS/JS instead if you want to be standards compliant.
The JQuery answer didn't work for me because my anchor tag is on a form and on my forms I use asp field validators and they just weren't playing nice. This led me to finding a pretty simple answer that doesn't require JQuery or CSS...
<a id="btnSubmit" href="GoSomePlace">Display Text</a>
You can disable the element and it should behave as input types do. No CSS needed. This worked for me in chrome and ff.
function DisableButton() {
var submitButton = document.getElementById("btnSubmit");
if (submitButton != null) {
submitButton.setAttribute('disabled', 'disabled');
}
}
Of course you'll be doing a loop to disable all anchor tags in the DOM but my example shows how to do it for just one specific element. You want to make sure you're getting the right client id of your element but this worked for me, on more than one occasion. This will also work on asp:LinkButtons which end up being anchor tag elements when rendered in the browser.
I am creating a website and i want to allow personalization to individual users upto some extent like changing font family, background color etc. The problem with this is that, my default css file that i load has already default classes for everything. Now when i fetch the background color from my database, then if there is null value for background color then default css class of mystylesheet.css should be loaded and if the value is not null, then i want to override this with my default css. How is it possible? Thanks in advance :)
Load the default stylesheat in a style tag, and put your dynamic styles in a style tag after that.
Which style to use when different styles target the same element is determined by specificity, and if the selectors are the same, by order. The style that is found last is used.
The approach mentioned by zaf would require that you reload the page when you want to switch styles sheets. What I find to be a better approach is to add a classname to the body
if you have the option of using javascript
<body class="theme-1">
<div class="main"><div>
</body>
Then each of your style sheets should contain the theme name in the declarations:
--theme1.css
.theme-1 div.main {
background-color: #eee
}
--theme2.css
.theme-2 div.main {
background-color: #f30
}
To switch style sheets, you just remove the old theme name and add the theme you want to use.
Then you can even add style sheets dynamically if you provide an interface for the user to customize the look and feel of your page.
New Improved Answer:
I just found a nice solution implemented by the folks at extjs. It involves loading all the stylesheets you want using <link> tags. The trick is that you can set a disabled property on the link element which will cause it not to apply.
For an example, use firebug and look at
http://www.extjs.com/deploy/dev/examples/themes/index.html
Look for styleswitcher.js and look at the function setActiveStyleSheet
function setActiveStyleSheet(title) {
var i,
a,
links = document.getElementsByTagName("link"),
len = links.length;
for (i = 0; i < len; i++) {
a = links[i];
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if (a.getAttribute("title") == title) a.disabled = false;
}
}
}
EDIT:
Reason for CSS property precedence?
One way is to produce the css file dynamically from a php script.
You would include the file like:
<link rel="stylesheet" type="text/css" href="css.php">
And the css.php file would look something like this:
<?php
header('Content-type: text/css');
// whatever you want to ouput depending on the user
?>