I am trying to set pointer-events: none for a div through JavaScript, however the property is not being applied.
I have tried:
document.getElementById("div").setAttribute("pointer-events", "none");
And:
document.getElementById("div").style.pointer-events = "none";
But neither worked, any ideas?
Your first attempt failed because it was a CSS property and not an attribute (part of the style attribute).
Your second attempt failed because for some off reason, when making this API casing-like-this gets converted to camelCasingLikeThis . This is likely because the folks who built JavaScript and the folks who built CSS weren't very well coordinated.
The following should work:
document.getElementById("div").style.pointerEvents = "none";
You can access style properties via Bracket notation like this:
document.getElementById("div").style['pointer-events'] = 'auto';
No need in camel case modification in this case.
There is an example in a book which uses element.setAttributeNS(null, "pointer-events", "none"); instead of using element.style.pointer-events = "none";.
Related
I have to use Google Tag Manager to make a change to fix something temporarily until I gain access to the back-end of a site. I am trying to remove a div container based on class. I have been able to successfully create a custom HTML tag with the following code to add remove the div container like so:
<script>
function changeHtml ()
{
document.getElementsByClassName("signup")[0].style.display = "none";
}
change = changeHtml();
</script>
The issue is that the problematic item in this div container is a form. I quickly found out that if you apply display: none; via css the form still works. The true way to remove this would be to remove it from the DOM. I tried adding the following JS but not having any success:
<script>
const elem = document.getElementsByClassName('signup');
elem.parentNode.removeChild(elem);
</script>
Receiving error:
Javascript Compiler error: Error at line 3, character 1: This language feature is only supported for ECMASCRIPT6 mode of better: const declaration
Use remove() method to remove the selected element from the DOM:
<script>
document.getElementsByClassName('signup')[0].remove();
</script>
You could achieve this easily by trying this instead
<script>
const elem = document.getElementsByClassName('signup')[0];
elem.outerHTML = '';
</script>
As of now, GTM supports ES6 only in custom templates, so the use of const in a custom javascript tag will result in an error. Your description is somewhat generic ("does not work"), so will just assume that this is your problem. Also your tag must be executed only after the element you want to remove actually exists (on DOM ready, or with a visibility trigger).
I'm using shadow dom to avoid my element's style from accidently affected by the host document,but it still inheritance some attributes from the parent,like the 'color','font-size','line-height',etc.
After searching google,I have found that there exists one attribute which can be used to achieve this,and it's the 'resetStyleInheritance' attribute.
I use the attribute like this:
var root = this.createShadowRoot();
root.resetStyleInheritance = true;
or add a 'reset-style-inheritance' attribute the the element,like:
<div reset-style-inheritance=true></div>
However,both cases didn't work.
I also found a bug report here:WebKit Bugzilla
My jsfiddle: http://jsfiddle.net/sangelee/90za0euy/1/
Why the resetStyleInheritance didn't work?Or are there any other solution to prevent style inheritance in shadow dom?Any help is appreciated!
ps.I'm using chrome 39,and just ignore other browsers.
First of all, the reset-style-inheritance attribute is now obsolete and should not be used. The shadow DOM is now not to be affected by light CSS anymore by default.
Your code contained an amount of glitches I get rid of (like you were creating the font-ruler prior to registering it, and you were handling attachedCallback while the proper event to handle is createdCallback.) The working version live is located here: http://jsfiddle.net/284au4nw/
A couple comments:
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var t = document.querySelector('#s-font-ruler-template');
this.createShadowRoot().appendChild(t.content);
}
}
});
document.registerElement('font-ruler', {prototype: proto});
— is appending the template content to your shadow root. You do not need to import node in the existing document (which seems to cheat Chrome and force it to apply light styles... uhm... well... somewhen.)
<font-ruler></font-ruler>
— in HTML is absolutely the same as
var font_ruler = document.createElement('font-ruler');
document.body.appendChild(font_ruler);
so I tried to keep everything as clear as possible. Hope it helps.
Use the CSS all property, it is a replacement for resetStyleInheritance
I have inline css in my element which i do not want. There is a lot of js in my website and i do not know from where this css is coming.
Any help will be great.
Thanks in advance.
If I were you, I'd use removeAtrr() to remove all the inline style for that element:
$('#yourElementId').removeAttr("style");
After that, I'll set any style again through external css file or javascript if necessary.
Or if you want to override the inline styles, you can also try to use !important attribute in css.
I think the most solid way to do it would be to use the browser's dev tools to run through the js one line at a time. This will show you the exact point in the code execution where the style is added. Here's a link demonstrating how to use breakpoints: https://developers.google.com/chrome-developer-tools/docs/javascript-debugging#breakpoints
Otherwise, if you're confident the code will be jQuery functions, do a search for .css(. If it's possible the change is made without jQuery, search for .style.. Some other possibilities are fadeIn, fadeOut, and animate. Once you find any of these, you can track what element they are being applied to to determine if they are relevant to the element you want to change.
Here are some selectors to look out for (vanilla JS and jQuery)
ClassName
document.getElementsByClassName('some-class');
$('.some-class');
ID
document.getElementById('some-id');
$('#some-id');
TagName
document.getElementsByTagName('tagNameHere');
$('tagNameHere');
QuerySelector
document.querySelector('cssSelectorHere');
document.querySelectorAll('cssSelectorHere');
$('cssSelectorHere');
If the problematic CSS is set with jQuery, you can hook into jQuery's cssHooks API to see when a particular CSS is being set. For example, if the problematic CSS is "margin-right" you can detect when it is being set and throw an exception so you can trace it through the browser's debugger:
var targetElement = document.getElement("checkme");
$(function() {
$.cssHooks["marginRight"] = {
set: function(node, value) {
if(node == targetElement) {
throw "stop that!";
}
else node.style.marginRight = value;
}
};
});
It seems that javascript only can ready inline css if i want to check if element is display:hidden getting it with:
el.style.display
But how to check if display:none is placed inside external CSS file?
You'll need to access the computed style of the element with getComputedStyle (standards-compatible browsers) or currentStyle (IE). Google for those terms for examples or use a framework such as jQuery, which provide wrappers for that.
It might be the backwards way and not helpful in this case, but anyway:
If you want to check out what's in the loaded CSS files, you can get the loaded stylesheets with var sheets = document.styleSheets;, and access the first one with sheets[0];
Then, get the rules from it:
var rules = sheets[0].cssRules ? sheets[0].cssRules : sheets[0].rules;
Then loop through the rules to check them out:
var rule, selector;
for (var idx=0, len=rules.length; idx<len; ++idx) {
rule = rules[idx];
selector = rule.selectorText;
if (!selector) {continue;}
console.log(selector+' => '+ rule.style.cssText);
}
This is more or less straight from David Flanagan's great book "Javascript, the Definitive Guide (5th ed.)"
if(el.style.display=='none') will work regardless of where the CSS is defined.
In firefox, I have the following fragment in my .css file
tree (negative){ font-size: 120%; color: green;}
Using javascript, how do I change the rule, to set the color to red?
NOTE:
I do not want to change the element.
I want to change the rule.
Please do not answer with something like
...
element.style.color = 'red';
What you're looking for is the document.styleSheets property, through which you can access your css rules and manipulate them. Most browsers have this property, however the interface is slightly different for IE.
For example, try pasting the following in FF for this page and pressing enter:
javascript:alert(document.styleSheets[0].cssRules[1].cssText)
For me that yields the string "body { line-height: 1; }". There are methods/properties that allow you to manipulate the rules.
Here's a library that abstracts this interface for you (cross-browser): http://code.google.com/p/sheetup/
function changeCSSRule (stylesheetID, selectorName, replacementRules) {
var i, theStylesheet = document.getElementById(stylesheetID).sheet,
thecss = (theStylesheet.cssRules) ? theStylesheet.cssRules : theStylesheet.rules;
for(i=0; i < thecss.length; i++){
if(thecss[i].selectorText == selectorName) {
thecss[i].style.cssText = replacementRules;
}
}
};
You can change CSS rules in style sheets through the CSS Object Model (currently known as DOM Level 2 Style). However, if you literally have "tree (negative)" in your style sheet that rule will be dropped and not appear in the Object Model at all.
As there is no HTML element tree I am going to assume that tree is the id or class of another element.
You would first retrieve the DOM element by id:
var tree = document.getElementById("tree");
Now tree represents your DOM element and you can manipulate it any way you like:
tree.style.color = "red";
Here is a great reference for mapping css properties to their javascript equivalent.
I'm not sure you can do actual class/selector overrides. You would need to target each element that used the .tree class and set the CSS. The quickest and easiest way would be through jQuery (or another similar framework):
$('.tree').each(function() { this.style.color = "red"; });
You could even use the built-in CSS functions:
$('.tree').css('color', 'red');
(I did it the first way to show you how standard JS would do it. The $(...) part is jQuery for selecting all elements with the .tree class. If you're not using jQuery, you'd need alternative code.)
If tree is an ID, not a class (there should only be one on the page) so using getElementById should be fine. Your code should look like the other answer.
for( var i in document.getElementsByTagName("tree") ){
document.getElementsByTagName("tree")[i].style.color = "red";
}
As I said in another answer's comment, I've never seen this done how you want. I've only ever targeted elements the same way as the CSS renderer would and changed each element style.
I did see this though: jQuery.Rule
It sounds like it does what you want but the demo causes my browser to flip out a bit. I'd invite you to look at the source to see it really does do what you want, and if you want to use it without jQ, use it as a starting point.
Edit: yes this should work. It works by appending another <style> tag to the page and writing out your overrides within. It's fairly simple to follow if you wanted to port it to plain JS.
For debugging, you can use Firebug to change the CSS rules on-the-fly.
If you want to change the rendered css rules from one page request to the next then some sort of server-side scripting will be required. Otherwise the original style sheet would simply reload at the next page request.
If you want to use an event on the first page to force the server-side action then you can use AJAX to actually change the CSS rule for the user.
"I want to change the rule so that
when I navigate to the next page, I
don't have to make all the changes
again."
It sounds like what you might want then is a remote request ("ajax") back to the server with the request you want to make, and generate a dynamic stylesheet which is sent back to the client?
How/why is this Firefox specific?
I want to change the rule so that when I navigate to the next page, I don't have to make all the changes again.
There are two approaches I can think of here. Namely client side and/or server side.
Client side:
Store the theme setting into cookies and load them up next time by javascript.
Server side:
If your site have an login system, you may also store the user preference into the database and generate the webpages with this inforamtion in mind next time on.
Utimately, you are still writing things like element.style.color =. But, they should get what you want.