Remove JavaScript styles, allowing CSS to take control - javascript

Preamble: Possible duplicate to my question can be found found here, although for me, this question was not sufficiently answered. A work-around is given, but a definitive answer to the question of whether or not it is possible, is not provided.
The question:
On my website, when a user clicks a button (or area of screen), I want that area to "flash" a couple of times before returning to its original state. (I think this gives the user a reassuring feel of something having been activated, as in some circumstances, they may have short delay before the feedback is given.)
Anyway, I've managed to get this working using a bit of JavaScript and jQuery, and you can see the results here >>.
As you may notice, the problem is that after the flashing is done, the element doesn't return to its original state. Rather, it keeps its last "flash" state, and overrides the underlying CSS styling which originally styles the object when the page loads.
I style the element with the following jQuery:
$jq_obj.css('background-color',flash_fg_color_).css('color',flash_bg_color_);
And I 'attempt' to un-style it with:
$jq_obj.removeAttr('background-color').removeAttr('color');
I've also tried:;
$jq_obj.css('background-color','').css('color','');
Despite the documentation saying that this should remove styling, it doesn't.
Is there a solution, or do I have to revert to the work-around solution referred to in my preamble? The nice thing about the JavaScript option is that it becomes a lot more versatile when you want to play around with the animations a bit.
Thanks,
===EDIT 2014-06-28===
As a demonstration of why the class solution is untidy, please see this fiddle: http://jsfiddle.net/Y9L4x/ (inspired by #BiffMaGriff 's proposed solutin here: http://jsfiddle.net/rte3G/)
The problem is that the elements being flashed could already be CSS-ed up to the hilt with multiple classes.
I recognise that I can remove styling classes first, before applying the "flash" classes, complicate the JavaScript and/or the CSS rules, etc. etc.
But the whole point of looking for a non-class-solution is that this option becomes extremely verbose in a real world situation, and you tend to have to program each flashing object individually, rather than the tidy one-JavaScript-function-fits-all that I'm searching for.

You are going to want to do your styles as classes.
.activated{
background-color: red; //or whatever else
}
and then with your jquery you can just toggle them a few times with the delays I assume you already have in your javascript.
$jq_obj.toggleClass('activated');

Try this:
$jq_obj.attr('style','');

The direct answer to the question appears to be a simple "No".
You cannot tell JavaScript to style an object, and then at a later stage, ask JavaScript to give styling responsibility back to CSS.
However, another messy work-around is to re-draw the HTML inside the element which contains your flashing-object.
$jq_flashing_obj.parent().html(original_html_);
This has the slight overhead of having to wrap your flashing object inside a div or span element, to ensure that the parent element contains nothing but your flashing element.
<div class="multiple-children">
link 1
<span class="wrapper">Click me to watch me flash</span>
link 3
</div>
You then, of course, have to capture the outerHTML of your flashing-object before the flashing starts.
original_html_ = $jq_obj[0].outerHTML;
The resulting JavaScript is a little bit verbose, as you see here: http://jsfiddle.net/CgsLs/ . However, it does have the following benefits:
Reusable on all clickable elements regardles of CSS :hover and other messy styling
Can optionally define the flash-color of the element inside the JS
Independent of CSS, meaning that the code is in one file, and therefore more maintainable
There are down-sides too
Requires the use of JQuery on() function (as opposed to simple click event handler)
Anyhoo... it may not be a solution for everyone. In some cases (maybe even most cases) the class option might be simpler.
But this is one other possible method of tackling this inherent shortcoming in JavaScript/Browser technology.

Related

Convenient way to get input for puppeteer page.click()

Challenge
When using puppeteer page.click('something') one of the first challenges is to make sure that the right 'something' is provided.
I guess this is a very common challenge, yet I did not find any simple way to achieve this.
What I tried so far
In Google Chrome I inspect the element that I want to click. I then get an extensive element description with a class and such. Based on an example I found, my approach is now:
Take the class
Replace all spaces with dots
Try
If it fails, check what is around this and add it as a prefix, for example one or two instances of button.
This does not exactly feel like it is the best way (and sometimes also fails, perhaps due to inaccuracies from my side).
One thing that I notice is that Chrome actually often seems to give a hint hovering over the thing I want to click, I am not sure if that is right but I also did not see a way to copy that (and it can be quite long).
If there is a totally different recommended way (e.g. Looking in the browser for what the name roughly is, and then using puppeteer to list all possible things), that is also fine. I just want to get the right input for page.click()
If you need an example of what I am trying: If you open this question in an incognito tab, you get options like share or follow. Or if you go to a web shop like staples and want to add something to cart.
When using puppeteer page.click('something') one of the first challenges is to make sure that the right 'something' is provided.
Just to be clear, "something" is a CSS selector, so your question seems to reduce to how to write CSS selectors that are accurate. Or, since Puppeteer offers XPath and traditional DOM traversals, we could extend it to include those selection tools as well.
Broader still, if there's a data goal we're interested in, often times there are other routes to get the data that don't involve touching the document at all.
I guess this is a very common challenge, yet I did not find any simple way to achieve this.
That's because there is no simple way to achieve this. It's like asking for the one baseball swing that hits all pitches. Web pages have messy, complex, arbitrary structures that follow thousands of different conventions (or no conventions at all). They can serve up a slightly or completely different page structure on any request. There's no silver-bullet strategy for writing good CSS selectors, and no step-by-step algorithm you can apply to universally "solve" the problem of accurately and robustly selecting elements.
Your goal should be to learn the toolkit and then practice on many different pages to develop an intuition for which tools and tricks work in which contexts and be able to correctly discern the tradeoffs in different approaches. Writing a full guide to this is out of scope, and articles exist elsewhere that cover this in depth, but here are a few high-level rules of thumb:
Look at context: consider the goals of your project, the general structure of the page and patterns on the page. Too many questions on Stack Overflow regarding CSS selectors (but also in general) omit context, which severely constrains the recommendation space, often leading to an XY problem. A few factors that are often relevant:
Whether the scrape is intended to be one-off or a long-running script that should try to anticipate and be resillient to page changes over time
Development time/cost/goal tradeoffs
Whether the data can be obtained by other means than the DOM, like accessing an API, pulling a JSON blob from a <script> tag, accessing a global variable on the window or intercepting a network response.
Considering nesting: is the element in a frame or shadow DOM?
Considering whole-page context: which patterns does the site tend to follow? Are there parent elements that are useful to selecting a child? (often, this is a distant relationship, not visible in a screenshot as provided by OP)
Consider all capabilities provided by your toolkit. For example, OP asked for a selector to close a modal on Stack Overflow; it turns out that none of the elements have particularly great CSS selectors, so using Puppeteer to trigger an Esc key press might be more robust.
Keep it simple: since pages can change at any time, the more constraints you add to the selector, the more likely one of those assumptions will no longer be true, introducing unnecessary points of failure.
Look for unique identifiers first: ids are usually unique on a page (some Google pages seem to scoff at this rule), so those are usually the best bets. For elements without an id, my next steps are typically:
Look for an id in a close parent element and use that, then select the child based on its next-most-unique identifier, usually a class name or combination tag name and attribute (like an input field with a name attribute, for example).
If there are few ids or none nearby, check whether the class name or attribute that is unique. If so, consider using that, likely coupled with a parent container class.
When selecting between class names, pay attention to those that seem temporary or stateful and might be added and removed dynamically. For example, a class of .highlighted-tab might disappear when the element isn't highlighted.
Prefer "bespoke" class names that seem tied to role or logic over generic library class names associated with styling (bootstrap, semantic UI, material UI, tailwind, etc).
Avoid the > operator which can be too rigid, unless you need precision to disambiguate a tree where no other identifiers are available.
Avoid sibling selectors unless unavoidable. Siblings often have more tenuous relationships than parents and children.
Avoid nth-child and nth-of type to the extent possibe. Lists are often reordered or may have fewer or more elements than you expect.
When using anything related to text, generally trim whitespace, ignore case and special characters where appropriate and prefer substrings over exact equality. On the other hand, don't be too loose. Usually, text content and values are weak targets but sometimes necessary.
Avoid pointless steps in a selector, like body > div#container > p > .target which should just be #container .target or #container p .target. body says almost nothing, > is too rigid, div isn't necessary since we have an id (if it changes to a span our new selector will still work), and the p is generic--there are probably no .targets outside of ps anyway.
Avoid browser-generated selectors. These are usually the worst of both worlds: highly vague and rigid at the same time. The goal is to be the opposite: accurate and specific, yet as flexible as possible.
Feel free to break rules as appropriate.

Setting (ARIA) role for HTML custom elements without explicit attribute?

I have a web app that displays and passes around user-editable semantic markup. For a variety of reasons, including security, the markup consists entirely of custom elements (plus the i, b, and u tags). For regular rendering, I simply have styles for all the tags and stick them straight in the DOM. This looks and works great.
Now I'm doing screen-reader testing, and things aren't great. I have a bunch of graphical symbols I want to add labels for. I've got divs that I want to make into landmarks. I've got custom input fields and buttons.
It would be easy enough to just add role= to all the different tag instances. But part of the reason for the custom markup is to eliminate all the redundant information from the strings that get passed around (note: they're also compressed). My <ns-math> tag should always have role="math", and adding 11 bytes to what might be tags around a single character is an actual problem when multiplied out over a whole article. I know this because the app started with a bunch of <span class="... type elements instead of custom.
For the fields and buttons, I've used a shadow DOM approach. This was necessary anyway to get focus/keyboard semantics correct without polluting the semantic markup with a bunch of redundant attributes, so it's easy to also slap the ARIA stuff on the shadow elements. Especially since the inputs are all leaf nodes. But most of my custom tags amount to fancy spans, and are mostly not leaf nodes, so I don't really want to shadow them all when they're working so well in the light DOM.
After a bunch of searching, it seems like the internals.role property from "4.13.7.4 Accessibility semantics" of the HTML standard is maybe what I want. I may well be using it incorrectly (I'm a novice at front-end), but I can't seem to get this to work in recent versions of Firefox or Chrome. I don't get an error, but it seems to have no effect on the accessibility tree. My elements are not form-associated, but my reading is that the ARIAMixin should be functional anyway. This is maybe a working draft? If this is supposed to work in current browsers, does anybody have a code snippet or example?
Is there some other straight-forward way to achieve my goal of accessibility-annotating my custom elements without adding a bunch of explicit attributes to the element instances?
So you want the benefit of adding a role or an aria-attribute without actually adding those attributes? The concept of an "accessibility object model" (AOM) has been bantering around a bit that would let you access and modify the accessibility tree directly but it's still in the works. Here's an article from a couple years ago that talks about it. Nothing official. Just one person's thoughts.
Further research shows that, as of this time, the abstracted accessibility options I'm asking for are not yet implemented.
For the time being: eliminating a number of page-owned enclosing divs from the accessibility hierarchy via role="presentation" significantly improved my overall tree. With those out of the way, the majority of my custom tags seem to be simply semantically ignored. This is mostly fine as the majority of my content is plain text.
Since I already mark up the vast majority of even single-character symbols, I've simply added all my symbols to the markup generator. Since everything is already in custom tags, I then use a shadow DOM span with role="img" and a character-specific aria-label to present the symbolic character.
My solution is still incomplete. I wish that I could convey the full richness of the semantic content I have available.

How to modify a large number of elements in DOM without sacrificing usability?

I have a list with quite a few elements (each of them is a nested div). Each element has a custom onclick handler.
JS updates the list several times per second, this may result in:
adding or removing some elements
changing text in some elements
changing styles in some elements
changing height of some elements
etc.
Most of the time the update makes small changes to the majority of the elements.
To minimize reflows I should remove the list from DOM, make the changes and append it back. The problem I have with this approach is that when user selects some text, the next update will reset the selection. (And the next update comes within a second) If user clicks a button his click may fail to register if there was an update between mose_down and mouse_up.
I understand when the selection resets on text that have been changed. It makes sense. But with such approach any selection in this list will reset.
Is there any better way to do this? How would you implement such list?
This list is fully generated by JS. If I'm removing it from DOM anyway, is there any benefit to modifying it instead of recreating it from scratch? Creating it anew each time would require less code.
This sounds like 2 way data binding, there are a couple of good custom solutions to data-binding answers on here: Handy stack link. Alternatively backbone.js and knockout.js have good techniques amongst quite a few other frameworks (angular ect).
Additionally, if you want to have a pop at it yourself (which I highly recommend to get a better understanding) you could use the proposed 'Object Observe' function. There's some handy documentation with some examples on how this works over at Mozilla. as well as The trusty HTML5 Rocks, which is a nice simple tutorial on using the new Object.Observe functionality, well worth a read.
Hope this helps!

which is one more expensive to call? showing-hiding a dom node or creating-deleting a dom node

Which is one more expensive to call?
showing-hiding dom node or
creating-deleting dom node
Assume there is only 1 dom or a few (less than 5) nodes that we need to manipulate and the application runs on desktop.
For a small number, does it even matter at all?
How about for mobile applications?
The difference between the two will be infinitesimally small for only a few elements -- it could absolutely be considered negligible.
That being said, showing and hiding the element via CSS will be faster unless you use jQuery's .show() and .hide(). jQuery's .hide() is much slower than any other method of hiding an element. If you'd like to know why, read the "Why is .hide() slower?" section at the bottom of my answer.
Anyway, you should make your decision based on which method suits your needs best. If you don't ever need the element again, you may as well delete it. If you just wan't to hide it for a little while or under certain conditions, show/hide it.
But if you want to test it yourself, here ya go :)
Why is .hide() slower?
jQuery's .hide() is basically the same as using .css('display','none') except that it caches the previous value of the display style, so that when you call .show(), your element will be correctly reverted to look the exact same as it did. If it had display:inline, it'll have it when it gets re-shown. If it had display:block, it'll have display:block. This can be pretty useful.
Here's an example:
lets say we have a div with id="myDiv" and it is styled in an external file with display:inline. We want to hide it.
With the .css way, we'd do this:
$('#myDiv').css('display','none');
and then later on sometime, one of your fellow developers wants to show it again under certain conditions. He'll have no idea what the display property should be, since the css is in an external file somewhere. Most developers default to display:block, like this:
$('#myDiv').css('display','block');
However in this case, we'd get a totally different style, since it was originally inline. A clever developer will have no problem figuring out what went wrong, but not all developers are clever :)
With .show() and .hide(), this becomes a non issue. We don't care what style it used to have. We just want it to be back where it was, and that's exactly what it'll do.

How to detect struckthrough text using JavaScript

I have a form which presents the user a list of checkboxes, some of which have the text label struckthrough some don't depending on initial conditions. This is functioning fine. During the form validation however, I would like to be able to detect which are struckthrough. I can figure out how to check if they're enabled, but whether the label is struckthrough is eluding me. Any ideas?
You'll have to use the DOM methods (or jQuery) to look at the parent element of the text to see if its a <del> tag.
Can you provide some sample source so I might be able to elaborate with an example.
Doing this with jQuery just makes so much more sense then trying to mess around with plain Javascript. Here is what you need, basically:
striked = $("strike"); // As mentioned, you should use `del` .. strike is depreciated
$.each(striked, function(i, el) {
alert($(el).html() + " is striked through. What do you want to do with it?");
});
Not sure what you want, but that would detect all elements with strike/del on your page. You can also change the search a bit, to restrict it to only within a certain form/div/whatever like so:
striked = $("strike", $("#myform_id"));
Hope that's what you were looking for.
If the strikeout (your struckthrough) is assigned via a CSS class, you can simple detect the class (since you can already detect enabled/disabled). Else like Darrell mentioned, jQuery will be a great method.
You basically have two categories of checkboxes which you are defining by their display qualities (struckthrough and not). This kind of "what does it look like" detection creates an artificial code-dependency which could cause a lot of trouble later:
The strikethrough effect can be accomplished in several ways (the del tag, the strike tag, CSS text-decoration: line-through, and possibly others in future versions of HTML/CSS). If you later change which way you do the effect, you'll have to update your js code to match
If you ever choose to reformat the list and stop using the strikethrough effect (e.g. you decide to make it invisible, or faded out, or have a red x over it), you will lose your ability to distinguish between the two types of checkboxes.
Instead, you should either assign a CSS class (like "nonUsableCheckboxes") to all strikethrough checkboxes, or generate a hidden field indicating if it is strikethrough or not. That way your javascript stays independent of your display code, and less prone to fail.

Categories

Resources