override default focus with css or reseting it - javascript

I want something like css reset, but only for the :focus. If there's none of this yet, would be good to know the possible properties to reset(override) in order to make new :focus that will override the previously one(set by the web-site css). For example, z-index may effect on :focus for some specific elements in some browsers. So the :focus should include z-index with some huge number and in order to work it should include position too. perhaps it's wrong example, but I think you got the idea here.

You may want to post some code with some examples of problems that you are having in a jsfiddle or in the question.
That said, there are some elements that tend to get default styling for :focus in the browser - input, a. There is some great information here about potential fixes, for instance:
/* put universal focus changes here */
*:focus {
outline: none;
}
/* put anchor focus changes here */
a:focus {
...
}
/* put input focus changes here */
input:focus {
...
}
I'm not certain what you are trying to accomplish with the z-index setting, but you could handle it as above.

Related

Disable waiting/busy cursor

Is there any way to completely disable waiting cursor ( ) in your web app/site so the user will never see it?
Or can I set a delay, so it will appear after one or two seconds, but not immediately?
update: Waiting cursor was shown on every http-request because of an angular-block-ui property autoBlock set to true (by default).
This will set the cursor to default, but it isn't a good practice to use !important, I suggest to find exactly the class that is setting to loading cursor and overwrite it
body {
cursor: default !important;
}
You can simply do it using pure JavaScript like this:
if (document.body.style.cursor==='wait') {
document.body.style.cursor='default';
}
But you need to know when run this script, but that's how you can detect and play with the cursor using JavaScript and use it depends on your need...
Also you use pure CSS, override all cursers on body and html like this:
body, html {
cursor: default !important;
}
or you can have 2 classes and toggle them in a certain time, for example, create class default-curser and apply it using JavaScript, when and where you need to override the curser!
Also the other way is having default curser for the body and html and override it later on in your css for different elements, like this:
body, html {
cursor: default !important;
}
a {
cursor: pointer !important;
}
//... and whatever other pointers you need
This way you always have default curser, expect otherwise!

Detect pseudo CSS activation

I have a DIV with the following CSS code attached:
.active,#foo:active {background-color: rgba(0,0,0,0.75)}
In addition, I have set up keydown and keyup javascript routines to convert a selected keypress to add and remove the 'active' class, darkening it accordingly. My problem is when the user clicks on the DIV (darkening it as expected)...but in a setInterval I have running, polling the DIV and several more like it periodically to get state information, I run into the problem of not being able to tell the current DIV state.
Getting the state via the active class is easy enough. I simply have to do this...
document.getElementById("foo").classList.contains("active")
That gives me a boolean on/off I can use, but the following does not work to read a mouse long click.
document.getElementById("foo").classList.contains(":active")
This is because activated pseudoes do not show up in classList. I tried rewriting the mouse-examining check to look like this:
document.getElementById("foo") === document.activeElement
But as the element is a DIV, this never resolves to a true as document.activeElement stays stuck on the BODY element of the page. I also tried looking at the current background-color, but the following doesn't update when :active is in use.
document.getElementById("foo").style.backgroundColor === "rgba(0,0,0,0.75)"
Is there another way to proceed without needing to resort to removing :active from the CSS and installing onclick() and onmouseout() to my code? Using that particular workaround does not scale well depending on how many DIVs I set up in this fashion. I would much rather detect when the DIV is currently using the CSS rule described above.
Please, no jQuery solutions or external libraries. I want to use vanilla JavaScript.
Pseudo elements are not part of the DOM so you cannot trigger events on them.
https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
In addition .style prototype function does not work as intended, to look for computed style use
var ele = document.querySelector('.example-value')
window.getComputedStyle(ele, null).backgroundColor === "rgba(0,0,0,0.75)"
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
Polling to get the current state of an element is a bad idea, instead use events.
When polling, you are making CPUs always process for nothing, it can make your page irresponsible, cause useless bottlenecks, but most of all, it consumes a lot of electricity for nothing. Always think about the trees when coding.
But one has to admit that for the :active status, it may be a bit cumbersome to listen to all the events that can trigger it.
So we've got to be a bit smarter, and create our own event from there.
We can create an empty animation triggered only in the :active state.
Then we just have to listen for the animationstart event to act as an replacement for our pseudo-class activation event.
/* older browsers might need vendor prefixes... */
foo.addEventListener('animationstart', function(evt){
// to be sure it's our correct event, we check for the animationName
console.log('active', evt.animationName === 'active');
});
#foo:active{
background-color: #FAFFAA;
-webkit-animation: active 0s linear;
-o-animation: active 0s linear;
-ms-animation: active 0s linear;
animation: active 0s linear;
}
#keyframes active{}
#-webkit-keyframes active{}
#-o-keyframes active{}
#-ms-keyframes active{}
<div id="foo">
click me to activate me
</div>
And if ever you need to know at any time if an element has an pseudo-class, you can use Element.matches(cssRule).
The word "active" has different meanings:
An element with the :active pseudo-class. This means the element is in the process of being clicked, usually. This is most commonly used for creating some visual effect when the user mouse-downs on a button, and remove it when he mouse-ups, for example. This is probably not relevant to your use case.
The element given by document.activeElement. This does not mean the element with the :active pseudo-class; it means the element with focus. It will be the body if there is no specific focus, or it could be some input element, or it could be any other element with a tabindex attribute. This is also the element with the :focus pseudo-class. An element can be focused by clicking on it, or tabbing to it, or calling HTMLElement#focus on it.
Some application-defined concept of "active", such as the currently active tab in a tabbed interface, often represented by the presence of a user-defined class on the element, such as your .active.
In general, people write far too much JavaScript to check things, or intercept events, or set magic variables, or add and remove classes or even local styles, or in the worst jQuery style add and remove elements from the DOM, or God forbid do polling, when in many cases CSS could handle what needs to be done if used properly. A trivial example is writing mouseover handlers when :hover could do the job.
I don't fully understand what you are trying to accomplish, or what the desired behavior is. However, the following code might give you some clues:
const activeElement = document.getElementById("activeElement");
const divElement = document.getElementById("div");
function showActiveElement() {
activeElement.textContent = document.activeElement.tagName;
}
function updateActiveElement() { setInterval(showActiveElement, 500); }
function setFocus() { divElement.focus(); }
updateActiveElement();
/* Show a message if the div is active (being clicked on). */
#activeMessage { display: none; }
#div:active ~ #activeMessage { display: block; }
/* Show a message if the div is focused. */
#focusMessage { display: none; }
#div:focus ~ #focusMessage { display: block; }
/* Style the div when it is focused. */
#div:focus { background-color: rgba(0, 0, 0, 0.75); color: white; }
#div { border: 1px solid gray; }
<p>
Here is the div we are working with.
Click on it, or tab to it, to give it the focus.
</p>
<!-- The div in question. Give it a tabindex to allow focus. -->
<div id="div" tabindex="1">
Hello Bob
</div>
<p id="activeMessage">
The div is active, in the sense that the mouse is being clicked on it, and
therefore its <tt>:active</tt> pseudo-class is set.
</p>
<p id="focusMessage">
The div is active, in the sense that it has the focus,
therefore its <tt>:focus</tt> pseudo-class is set.
<p>
The element with focus at the moment (<tt>document.activeElement<//tt>) is
<span id="activeElement"></span>
</p>
<button onclick="setFocus()">Make the div focused ("active")</button>

How to trigger bootstrap's mouseover effect programmatically

In twitter bootstrap, some elements get "greyed out" when the mouse hovers over them. This is true of buttons and linked list group items. Two examples are here: http://imgur.com/a/ABhkT#0
Can this effect be triggered programmatically? If so, how?
Yes, Using the 'onmouseover' attribute. It is quite similar to the 'onclick', except obviously for hovering instead.
Like the 'onclick', you will have to include a java script function that would change the css style for that element.
Depending on what you are trying to have this effect on, you could either put it right into the tag that is the object, or use <span></span>.
Ex:
<div onmouseover="fade()">
<p>text to fade</p>
</div>
Javascript:
function fade(){
code to change style
}
should be straight forward, this would fade everything inside the div (including the background)
Ok, I figured it out.
If the effect were being caused by a css class, one could simply apply the class to the element, like this:
$('<my_element>').addClass('bootstrapMouseoverGrey')
This doesn't work, though, because the effect isn't caused by a class. It's caused by a pseudoclass. Pseudoclasses can't be added programmatically.
One workaround is to create a new actual class with the exact same definition as the pseudoclass. In my case, the pseudoclass is a.list-group-item:hover, defined in bootstrap.css.
a.list-group-item:hover,
a.list-group-item:focus {
text-decoration: none;
background-color: #f5f5f5;
}
I edited bootstrap.css to make a new (actual) class, bootstrapMouseoverGrey, with the same definition as the pseudoclass.
a.list-group-item:hover,
a.list-group-item:focus,
.bootstrapMouseoverGrey {
text-decoration: none;
background-color: #f5f5f5;
}
Now, I can just add this class to an element using the line at the top of the answer. This gives me the result I want. Works like a charm!
Using jQuery:
var event = jQuery.Event('<event_name>');
event.stopPropagation();
$('<selector>').trigger(event);
Taken from the docs.

css: changing the ruleset vs using selectors to switch classes/apply styles

Lately I wondered about editing elements styles not by switching their classes on dom, but by changing the actual ruleset for the css class or selector.
So instead of something like
$('.some').hide()
or
$('.some').addClass('hidden')
Why not alter a rule directly with document.styleSheets and stuff?
Wouldn't this approach be generally more performant, at least with many elements, as we'd let the browser handle the ruleset changes natively?
You could for example add an style to .some, like display: none; and all .some elements would be immedeatly be hidden. There is no need to iterate over all those elements in js and hide them manually(like the example above).
Changing rulesets directly would more likely encourage classes that are context aware(or however you would call this..), as you'd hide all #persons > .item or something.
I still don't know best practices regarding classes that are named with context in mind, like for example control names like .calendar .ticket .item, versus single functionality classes like .hidden .left .green, as I usually need both types of conventions.
I am just asking what you think about this and what are benefits and drawbacks of the modifiying stylesheet approach versus how libraries like jquery handle changing styles?
Also, what do you think is good practice, what do you regard more as a hack?
cough javascript and hacking cough
Manipulating document.styleSheets is tricky due to differing implementations and the lack of a rule selector API. Currently if you want to manipulate a rule in a stylesheet you have to go through this process:
iterate over document.styleSheets
iterate over rules within current styleSheet object
if rule matches our class, edit the rule styles
Then there's the cascading issue. How do you know that a particular style on the rule you've matched won't be overridden by a different rule somewhere in the pages stylesheets? If you just bail out after changing the first matching rule you find, you can't be sure that the styles you set will actually be applied to the element, unless you stick an !important on each one, which will leave you with a whole different set of problems.
Even when you've manipulated the style sheet rules, the browser still has the same job to do — it has to recalculate all the styles by applying the cascade.
So, manipulating styleSheets doesn't look too appealing now, does it? Stick to class switching, trust me. Using jQuery and modern APIs like querySelectorAll make it plenty fast and the browser still does all the hard work like recomputing the style values.
Such a tricky question :(
But if you take boilerplate for instance, it has a some standard classes to use like:
/* Hide from both screenreaders and browsers: h5bp.com/u */
.hidden { display: none !important; visibility: hidden; }
/* Hide only visually, but have it available for screenreaders: h5bp.com/v */
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: ; position: absolute; width: 1px; }
/* Hide visually and from screenreaders, but maintain layout */
.invisible { visibility: hidden; }
Where it gets tricky is, IF it is something you need to hide because of JS, then you should ONLY hide it with JS. Then it will function if JS is disabled.
If it is something that is not JS dependent, then you hide it in the HTML.
So JS function = hide with JS (either by using JS or adding hide classes)
Basic HTML hide = hide with HTML class
Styleswitching vs JS switching
Basicly JS switching gives you the oppertunity to add effect etc, just using predefined classes limits that somewhat. But would love to see some ressource comparisons :)

How can I convince Firefox to redraw CSS Pseudo-elements?

I'm having issues getting Firefox to update a webpage when its class is changed dynamically.
I'm using an HTML table element. When the user clicks a cell in the table header, my script toggles the class back and forth between sorted_asc and sorted_des. I have pseudo element which adds an arrow glyph (pointing up or down) depending on which class the cell currently is.
.thead .tr .sorted_asc .cell:after {
content: ' \25B2';
}
The problem is, that when you click the cell header a second time, the page doesn't update the arrow... until the user mouses away from the element. I think it's a bug as it works fine in Safari, and as I don't see any :hover tags in my CSS or other entries that might interfere.
Anyone seen this before, or know how to work around the issue?
It's kind of cheesy, but since you're using javascript anyway, try this after you changed the className:
document.body.style.display = 'none';
document.body.style.display = 'block';
This will re-render the layout and often solves these kind of bugs. Not always, though.
This is 2014 and none of the proposed solutions on this page seem to work. I found another way : detach the element from the DOM and append it back where it was.
Would you be able to use different CSS to accomplish the same thing without relying on the :after pseudo-selector? You might be able to simple define a background-image which you align as needed (I assume you would want the arrow on the right hand side).
For example:
.thead .tr .sorted_asc .sorted_asc {
background: url(images/down_arrow.png) no-repeat right;
}
.thead .tr .sorted_asc .sorted_des {
background: url(images/up_arrow.png) no-repeat right;
}
I only suggest this since I assume there isn't a specific reason why you need to use the :after pseudo-class. If you do need to use it, please update.
The bug can still be triggered in Firefox 58. Thankfully the opacity trick also still works. Just make sure to time it correctly. You might need to set a timeout between opacity changes.

Categories

Resources