Apply css for pseudo elements using javascript [duplicate] - javascript

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 2 years ago.
How I can change CSS for a pseudo element style?
I am trying to get the CSS before:: rule and change left: to 95% or 4px.
How can I perform this in my context?
I've also made some test using document.querySelector but it doesn't work, I get a compute Read-Only error.
Do you have suggestions?
Example:
css
.iziToast-wrapper-bottomLeft .iziToast.iziToast-balloon:before {
border-right: 15px solid transparent;
border-left: 0 solid transparent;
right: auto;
left: 8px;
}
js
if(description_iziToast){
let RightMode = event.x>window.innerWidth/2;
let bubblePosition = document.getElementsByClassName("iziToast-balloon")[0]; // get the div that hold the bubble
let ajustScreenLR = RightMode && document.getElementsByClassName("iziToast")[0].offsetWidth || 0; // halfScreen ajustement
//bubblePosition.style.left = RightMode && '95%' || '4px'; // here i need to change the position in the befor:: attribut
description_iziToast.style.left = `${event.x-20-ajustScreenLR}px`;
description_iziToast.style.top = `${event.y-105}px`;
}
}else{
if(description_iziToast){ iziToast.destroy(); description_iziToast = false; };
}
Here the app console debug

Since pseudo-elements do not exist in the DOM, they cannot be accessed in Javascript.
The workaround is to create a <span> instead of using :before and the same logic has to be applied.

Here are two ways to directly manipulate a pseudo-element:
First way, is by using some sort of style manager.
This "manager" is an object with methods which allows easier manipulation of CSS rules on-the-fly, so here is a very basic example which you can study and implement for your specific needs:
var elm = document.querySelector('main');
// Reference: https://stackoverflow.com/a/28930990/104380
var styleManager = (function() {
// Create the <style> tag
var style = document.createElement("style")
// WebKit hack
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
function getStyleRuleIndexBySelector(selector, prop){
var result = [], i,
value = (prop ? selector + "{" + prop + "}" : selector).replace(/\s/g, ''), // remove whitespaces
s = prop ? "cssText" : "selectorText";
for( i=0; i < style.sheet.cssRules.length; i++ )
if( style.sheet.cssRules[i][s].replace(/\s/g, '') == value)
result.push(i);
return result;
};
return {
style : style,
getStyleRuleIndexBySelector : getStyleRuleIndexBySelector,
add(prop, value){
return style.sheet.insertRule(`${prop}{${value}}`, style.sheet.cssRules.length);
},
remove(selector, prop){
var indexes = getStyleRuleIndexBySelector(selector, prop), i = indexes.length;
// reversed iteration so indexes won't change after deletion for each iteration
for( ; i-- ; )
style.sheet.deleteRule( indexes[i] );
}
}
})();
elm.addEventListener('mouseenter', function(){
// each new rule should be added the END of the sheet
styleManager.add('main::before','left:90%; top:60%;');
styleManager.add('main::before','left:70%;');
});
elm.addEventListener('mouseleave', function(){
styleManager.remove('main::before', 'left:70%;'); // you can also try without the "left:70%;" part
});
main{
position:relative;
width: 200px;
height: 200px;
border: 1px dashed silver;
}
main::before{
content: 'pseudo';
width: 100px;
height: 100px;
background: lightgreen;
position: absolute;
left: 10px;
top: 40px;
transition:.3s ease-out;
}
<main>Hover & out</main>
Another way - with CSS variables:
var elm = document.querySelector('main');
elm.addEventListener('mouseenter', function(){
elm.style.setProperty('--before-left', '90%');
});
elm.addEventListener('mouseleave', function(){
elm.style.setProperty('--before-left', '10px');
});
main{
--before-left : 10px; /* <-- Your CSS should use variables for this to work */
position:relative;
width: 200px;
height: 200px;
border: 1px dashed silver;
}
main::before{
content: 'pseudo';
width: 100px;
height: 100px;
background: lightgreen;
position: absolute;
left: var(--before-left); /* <-- using the variable */
top: 40px;
transition:.3s ease-out;
}
<main>Hover & out</main>

Related

How to display all CSS selectors & properties in a textarea?

I am trying to display a set of CSS properties in a textarea using JavaScript:
var exampleone = document.getElementById('th001');
var borderbox = window.getComputedStyle(exampleone).getPropertyValue('cursor');
document.getElementById("csstextareadisp").value = borderbox;
However it only displays one element, which I have to specify.
I want the JavaScript to read all properties which exist in the CSS document and display them as seen in the CSS document, e.g.
.exone{
border-style: solid;
border-width: 2px;
border-color: rgba(57,165,255,1.00);
width: 150px;
height: 30px;
position: relative;
text-align: center;
background-color: transparent;
color: black;
}
.exone:hover{
cursor: pointer;
background-color: rgba(57,165,255,1.00);
color: white;
}
My question is, is there a way I can use JavaScript to get it to display like that (seen above) in a textarea other than setting it to display using:
document.getElementById("csstextareadisp").value = ".exone{ \n border-style: solid; \n border-width: 2px; \n border-color: rgba(57,165,255,1.00); \n width: 150px; \n height: 30px; \n position: relative; \n text-align: center; \n background-color: transparent;color: black; \n } \n\n .exone:hover{ \n cursor: pointer; \n background-color: rgba(57,165,255,1.00); \n color: white; \n }";
Updated answer
There is a helpful topic here:
How to get the applied style from an element, excluding the default user agent styles
I tried to enhance the solution provided in this topic to better fit your needs by…
Adding a parameter to be able to choose whether or not to include inline style,
Adding a function to correctly indent the styles,
Trying to simplify some code.
var proto = Element.prototype;
var slice = Function.call.bind(Array.prototype.slice);
var matches = Function.call.bind(proto.matchesSelector ||
proto.mozMatchesSelector || proto.webkitMatchesSelector ||
proto.msMatchesSelector || proto.oMatchesSelector);
// Returns true if a DOM Element matches a cssRule
var elementMatchCSSRule = function(element, cssRule) {
// console.log(cssRule) //.selectorText.split(":")[0]); // Testing to add hover
return matches(element, cssRule.selectorText);
};
// Returns true if a property is defined in a cssRule
var propertyInCSSRule = function(prop, cssRule) {
return prop in cssRule.style && cssRule.style[prop] !== '';
};
// Here we get the cssRules across all the stylesheets in one array
var cssRules = slice(document.styleSheets).reduce(function(rules, styleSheet) {
return rules.concat(slice(styleSheet.cssRules));
}, []);
// Get only the css rules that matches that element
var getAppliedCSS = function(elm) {
var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, elm));
var rules = [];
if (elementRules.length) {
for (i = 0; i < elementRules.length; i++) {
rules.push({
order: i,
text: elementRules[i].cssText
})
}
}
return rules;
}
// TAKIT: Added this function to indent correctly
function indentAsCSS(str) {
return str.replace(/([{;}])/g, "$1\n ").replace(/(\n[ ]+})/g, "\n}");
}
function getStyle(elm, lookInHTML = false) { // TAKIT: Added the new parameter here
var rules = getAppliedCSS(elm);
var str = '';
for (i = 0; i < rules.length; i++) {
var r = rules[i];
str += '/* CSS styling #' + r.order + ' */\n' + r.text;
}
// TAKIT: Moved and simplified the below from the other function to here
if (lookInHTML && elm.getAttribute('style')) // TAKIT: Using the new parameter
str += '\n/* Inline styling */\n' + elm.getAttribute('style');
return indentAsCSS(str);
}
// Output in textarea
var exone = document.getElementById("exone");
var result = document.getElementById("result");
result.value = getStyle(exone, true); // TAKIT: Using the new parameter for inline style
#exone {
border-style: solid;
border-width: 2px;
border-color: rgba(57, 165, 255, 1.00);
width: 150px;
height: 30px;
position: relative;
text-align: center;
background-color: transparent;
color: black;
}
#exone:hover {
cursor: pointer;
background-color: rgba(57, 165, 255, 1.00);
color: white;
}
#result {
width: 90%;
height: 240px;
}
<div id="exone" style="opacity: 0.95;"></div>
<textarea id="result"></textarea>
(I'm trying to add the :hover style to the output too, but I can't make it to work)
⋅
⋅
⋅
Old answer
(When I hadn't found anything helpful yet)
As the .getComputedStyle doesn't make any difference between the one that are present in the CSS and the other ones, it seems complicated to differenciate them.
So, here is an attempt of that:
I've made a loop to compare the element exone with another reference element that has not been stylized using CSS,
It seems that the element we take in reference must be on the page to effectively compare them, so I've put it in the HTML.
In the loop, if the values are the same, that must mean that both of them are not stylized, so, we skip to the next item.
I ended-up with that snippet:
// Get style of our example element
var exampleone = document.getElementById('exone');
var styles_one = window.getComputedStyle(exampleone);
// Get style of a reference element without CSS
var reference = document.getElementById('exref');
var styles_ref = window.getComputedStyle(reference);
// Loop and compare our example element with the reference element
var results = {};
for (var key in styles_ref) {
if(key.includes('webkit')) continue; // Next if webkit prefix
if(styles_one[key] == styles_ref[key]) continue; // Next if same value as the ref
results[key] = styles_one[key]; // Copy value in results[key]
}
delete results.cssText; // Useless in our case
// Output in console
console.log(results);
#exone {
border-style: solid;
border-width: 2px;
border-color: rgba(57, 165, 255, 1.00);
width: 150px;
height: 30px;
position: relative;
text-align: center;
background-color: transparent;
color: black;
}
#exone:hover {
cursor: pointer;
background-color: rgba(57, 165, 255, 1.00);
color: white;
}
<div id="exone"></div>
<div id="exref"></div>
The console should display only the CSS that differs from the not stylized reference element… So, this must come from the CSS!
Now, we only need to format a little this output and put it in a textarea.
Feel free to comment.
Hope it helps.

How to call access pseudo elements styling from Javascript? [duplicate]

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 6 years ago.
Earlier my question was:-
I have the following code in my Sass css file
.random {
box-sizing: content-box;
text-align: center;
line-height: 1;
&:before {
display: inline-block;
margin-right: 0.2em;
width: 0;
height: 0;
border-right: 0.4em solid transparent;
border-left: 0.4em solid transparent;
content: "";
vertical-align: baseline;
}
}
.perc-neg:before {
border-top: 0.5em solid #FCB062;
}
.perc-neg.good:before {
border-top: 0.5em solid #98F1AC;
}
I have a div with
class = "random perc-neg good"
Now I want to change style of the above div. how to do it?
I tried following in console but it returns empty object
$("random perc-neg good:before").css("color","red");
$("random.perc-neg.good:before").css("color","red");
$(".random.perc-neg.good:before").css("color","red");
Someone has suggested its a possible duplicate but its not.
Int he related question, the user just wanted to make it visible or hidden so two classes will be sufficient.
But my requirement is to change the color as per user's choice which he can select from wide range of colors.
Its definitely impossible to define a class with each color changes.
And we cant pass some variable to css as well to change the color property accordingly.
Updated Question:
I am now using Sass.
I have defined an function to update the color
#function em($color) {
#return border-bottom: 0.5em solid $color;
}
.perc-neg.good:before {
em(#98F1AC);
}
definitely, I can call the function from the Sass file but how to call it from javascript
Now I want to pass the hex code of color from javascript
I need to pass something like this from javascript
.perc-neg.good:before(#98F1AC)
looked for the same in google did not find anything relevant
Instead of marking it as duplicate, it would be much better if you can provide a solution
You cannot access pseudo elements in Javascript since these elements are not in the DOM.
If you want the change pseudo elements styling, you need to predefine css classes for that purpose and add/remove those based on your triggering events.
If that is not possible, simply don't set the colorproperty on the pseudo element at all, but on the host element, since :before and :after will then inherit their host element's color property (if they don't have a specific color property assigned to themselves in CSS).
You cannot call a SASS / LESS function from javascript as they are both pre-compilers that just produce a static stylesheet.
If you have a limited color pallet you could create all the rules that cover your use cases.
However you do have the ability to create a style element with javascript and append new rules to it. Here is a simple example that you could expand on
// add Style is wrapped in a closure that locks in a single
// style element that you can add to on the fly
const addStyle = (() => {
// create and append the style element
const styleSheet = document.createElement('style')
document.head.appendChild(styleSheet)
const style = styleSheet.sheet
// helper function to serialize an object to a css string
const serializeStyle = (styles) => {
return Object.keys(styles).reduce((str, prop) => {
return str + kebabCase(prop) + ':' + styles[prop] + ';'
}, '')
}
// helper function to convert camelCase to kebab-case
const kebabCase = (str) =>
str.replace(/([A-Z])/g, (_, letter) => '-'+ letter.toUpperCase())
// return the public function
return (selector, styles) => {
// add a new rule to the created stylesheet
style.insertRule(
selector + '{' + serializeStyle(styles) + '}',
style.cssRules.length
)
}
})()
addStyle('.random::before', {
border: '10px solid #aec369'
})
addStyle('.random::before', {
background: '#bada55',
boxShadow: '5px 5px 10px #777'
})
const el = document.querySelector('#color')
const em = () => {
addStyle('.random::before', {
borderColor: el.value
})
}
el.addEventListener('keyup', em)
el.addEventListener('change', em)
.random {
position: relative;
background-color: #eee;
}
.random::before {
content: '';
display: block;
height: 200px;
width: 200px;
}
<input id="color" placeholder="#000000" />
<div class="random">
</div>

Dynamically alter contents of a div and append to another div

So basically I have this div in body
<body>
<div id="main_content"></div>
</body>
Now I am downloading some data from the internet (a set of boolean data) and I have this div template. Let's say the data is (true, false, true). Then for each data I want to alter the template div. For example: first one is true so inside the template div I will change the sub1 div's height to 40 px; if it's false, I'd change sub2 div's height to 40 px; and then I'd append this modified template div to main_content div
Template div:
.child{
width:300px;
height:auto;
}
.sub1{
width:300px;
height:20px;
background-color:#0FF;
}
.sub2{
width:300px;
height:20px;
background-color:#F0F;
}
<div class="child">
<div class="sub1"></div>
<div class="sub2"></div>
</div>
After all this this should be the final output of main_content div
What would be the easiest way of doing this using HTML/CSS/JS.
Thanks
Short answer: Here is a codepen
Long answer:
I would use js to dynamically generate your template div:
function makeTemplateDiv() {
var child = document.createElement('div');
child.className = "child"
var sub1 = document.createElement('div');
sub1.className = "sub1"
var sub2 = document.createElement('div');
sub2.className = "sub2"
child.appendChild(sub1);
child.appendChild(sub2);
return child;
}
Then make a css class for a taller 40 px
.taller {
height: 40px;
}
Then use js to to alter your template based on a passed in value
function alterTemplateDiv(value) {
var template = makeTemplateDiv();
if(value) {
template.getElementsByClassName("sub1")[0].className += " taller";
} else {
template.getElementsByClassName("sub2")[0].className += " taller";
}
return template;
}
Then use js to pass in your array of values, make the divs, and append them
function appendDivs(arrayOfValues) {
var mainDiv = document.getElementById("main_content");
for(var i = 0; i < arrayOfValues.length; i++) {
mainDiv.appendChild(alterTemplateDiv(arrayOfValues[i]));
}
}
This kind of question begs for a million different types of answers, but I think this generally keeps with most best practices for front end coding without the use of a framework:
// Self-invoking function for scoping
// and to protect important global variables from other script changes
// (The variable references can be overwritten)
(function (window, document) {
var templateText,
generatedEl,
topEl,
bitArray;
// Data
bitArray = [true, false, true];
// Get template text
templateText = document.getElementById('my-template').text.trim();
// Loop through your T / F array
for (var i = 0, l = bitArray.length; i < l; i++) {
// Create a DIV and generate HTML within it
generatedEl = document.createElement('div');
generatedEl.innerHTML = templateText;
// Modify the new HTML content
topEl = generatedEl.getElementsByClassName('child')[0];
topEl.className += bitArray[i] ? ' typeA' : ' typeB' ;
// Insert generated HTML (assumes only one top-level element exists)
document.getElementById('my-container').appendChild(generatedEl.childNodes[0]);
}
})(window, document);
.child {
width: 300px;
height: auto;
}
/* For true */
.child.typeA > .sub1 {
width: 300px;
height: 40px;
background-color: #0FF;
}
.child.typeA > .sub2 {
width: 300px;
height: 20px;
background-color: #F0F;
}
/* For false */
.child.typeB > .sub1 {
width: 300px;
height: 20px;
background-color: #0FF;
}
.child.typeB > .sub2 {
width: 300px;
height: 40px;
background-color: #F0F;
}
<!-- Container -->
<div id="my-container">
<!-- HTML Template -->
<script id="my-template" type="text/template">
<div class="child">
<div class="sub1"></div>
<div class="sub2"></div>
</div>
</script>
</div>
Note that the HTML content, JavaScript code and CSS are all kept very separated. This is based on the concepts of "Separation of Concerns" and "Unobtrusive JavaScript". I invite you to read up on them if you haven't already. Also, front end templating can be used for dynamic content like I did here, but I would recommend doing templating on the back end when you can. It works better for SEO purposes.
jQuery makes it easier to manipulate the DOM, so here is another solution for your problem:
var data = [true, false, true];
for (i=0; i<data.length; i++) {
var height1;
var height2;
if (data[i] == true) {
height1 = 40;
height2 = 20;
}
else {
height1 = 20;
height2 = 40;
}
var div1 = document.createElement("div");
$(div1).toggleClass("sub1")
.height(height1)
.appendTo("#main_content");
var div2 = document.createElement("div");
$(div2).toggleClass("sub2")
.height(height2)
.appendTo("#main_content");
}

Calculating Paint Times of Elements In All Browsers

I am trying to calculate the elapsed time an element is painted onto the DOM from the start time of the script or if the specific element was even painted at all. I am inserting a background gradient to the HTML, and then using javascript to create random (clouds, which are just large periods with a text shadow) in multiple places across the screen (some negative, some positive, some within scope, some outside of scope).
Currently my code looks like this:
<html>
<head>
<style>
.container {
border: 1px solid #3b599e;
overflow: hidden;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#315d8c', endColorstr='#84aace'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#315d8c), to(#84aace)); /* for webkit browsers */
background: -moz-linear-gradient(top, #315d8c, #84aace); /* for firefox 3.6+ */
}
.cloud {
color: #fff;
position: relative;
font: 100% "Times New Roman", Times, serif;
text-shadow: 0px 0px 10px #fff;
line-height: 0;
}
</style>
<script type="text/javascript">
function cloud(){
var b1 = "<div class=\"cloud\" style=\"font-size: ";
var b2 = "px; position: absolute; top: ";
document.write(b1+"300px; width: 300px; height: 300"+b2+"34px; left: 28px;\">.<\/div>");
document.write(b1+"300px; width: 300px; height: 300"+b2+"46px; left: 10px;\">.<\/div>");
document.write(b1+"300px; width: 300px; height: 300"+b2+"46px; left: 50px;\">.<\/div>");
document.write(b1+"400px; width: 400px; height: 400"+b2+"24px; left: 20px;\">.<\/div>");
}
function clouds(){
var top = ['-80','80','240','400'];
var left = -10;
var a1 = "<div style=\"position: relative; top: ";
var a2 = "px; left: ";
var a3 = "px;\"><script type=\"text/javascript\">cloud();<\/script><\/div>";
for(i=0; i<8; i++)
{
document.write(a1+top[0]+a2+left+a3);
document.write(a1+top[1]+a2+left+a3);
document.write(a1+top[2]+a2+left+a3);
document.write(a1+top[3]+a2+left+a3);
if(i==4)
{
left = -90;
top = ['0','160','320','480'];
}
else
left += 160;
}
}
</script>
</head>
<body style="margin:0;padding:0;">
<div class="container" style="width: 728px; height: 90px;">
<script>clouds();</script>
</div>
</body>
</html>
I then run this inside of an iframe, trying to detect if the visible elements are being painted first, or if they are being painted in display order (pretty much, is the ad currently being viewed, or is it out of view).
I have not found a solid technique yet that works crossbrowser to detect this. In chrome, I was able to see it work when pasting images, as the visible images got an onload event fired first (even though they were at the end of the DOM), but this wasn't the case for firefox or IE.
I'm really not sure what you're after here. You said: "(pretty much, is the ad currently being viewed, or is it out of view)." But that is a bit cryptic.. What "ad" are you talking about?
In trying to figure out what you were trying to accomplish I pretty much rewrote your script to do exactly the same as before and it does an alert of the elapsed time as well as logs the time for each cloud in the console. It's not a good way to calculate execution time (which is what it seemed to me like you were after..).
NOTE: The only reason I rewrote everything was so I myself could make better sense of it in preparation for a response from you. Once I know exactly what you want I will edit my answer.
<style>
.container {
width: 728px;
height: 90px;
border: 1px solid #3b599e;
overflow: hidden;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#315d8c', endColorstr='#84aace'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#315d8c), to(#84aace)); /* for webkit browsers */
background: -moz-linear-gradient(top, #315d8c, #84aace); /* for firefox 3.6+ */
}
.cloud {
color: #fff;
position: absolute;
font: 100% "Times New Roman", Times, serif;
text-shadow: 0px 0px 10px #fff;
line-height: 0;
}
.cloud-container {
position: relative;
}
</style>
<div class="container"></div>
<script type="text/javascript">
// for IE
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
var pxTop = ['34px', '46px', '46px', '24px'],
pxLeft = ['28px', '10px', '50px', '20px'],
size = ['300px', '300px', '300px', '400px'];
function cloud(callback) {
var df = document.createDocumentFragment(),
node;
for (var i = 0; i < 4; i++) {
node = document.createElement('div');
node.className = 'cloud';
node.style.fontSize = size[i];
node.style.width = size[i];
node.style.height = size[i];
node.style.top = pxTop[i];
node.style.left = pxLeft[i];
node.innerHTML = '.';
df.appendChild(node);
}
callback && callback();
return df;
}
function clouds(containerId, callback) {
var top = ['-80','80','240','400'],
left = -10,
container = document.querySelector(containerId);
container.appendChild(document.createTextNode("\n"));
for (i = 0; i < 8; i++) {
var div = document.createElement('div');
div.className = 'cloud-container';
div.style.top = top[0] + 'px';
div.style.left = left + 'px';
console.log('About to start making a cloud', new Date().getMilliseconds());
div.appendChild(cloud(function() {
console.log('Finished making cloud', new Date().getMilliseconds());
}));
container.appendChild(div);
container.appendChild(document.createTextNode("\n")); // newline for view source
if (i == 4) {
left = -90;
top = ['0','160','320','480'];
} else {
left += 160;
}
}
callback && callback();
}
var start = new Date().getMilliseconds();
clouds('.container', (function() {
var end = new Date().getMilliseconds(),
time = end - this;
alert('Execution time: ' + time);
}).bind(start));
</script>
You should use console API for measuring timings more accurately (and avoid DIY spaghetti):
console.time("Doing stuff");
/*le code*/
console.timeEnd("Doing stuff");
This functionality is available natively in Chrome and Firefox; it can also be polyfilled on other browsers like IE but will not be as precise.
Note that using Date is not appropriate/intended for benchmarking:
Depending on the browser and OS, Date's resolution can be as low as 15 milliseconds.
Date based on system time, isn't ideal. Most systems run a daemon which regularly synchronizes the time... tweaked a few milliseconds every 15-20 minutes. At that rate about 1% of 10 second intervals measured would be inaccurate.
Update:
Hold on, are you trying to measure browser paints' timing and order? These can't be monitored through js (ok, it's possible to have a js API, but ultimately it has to be benchmarked in the browser engine, so no js polyfills).
Rule of thumb is elements will be painted in parse order, with re-paints/re-flows triggered by content styling - like backgrounds being loaded, additional css rules becoming available or content of different size being added into a table column.
Html5rocks on profiling long paint times might get you started in the right direction.

Adding Event Listeners in JavaScript

I have a JavaScript and divs defined using CSS3 classes. I need to add event listener to specific class div but it is not getting bound to it.
e.g.:
this._incrementEnabled = document.createElement('div');
this._incrementEnabled.className = this._incrementButtonProperties.enabledClass;
this.divElt.appendChild(this._incrementEnabled);
if (this.properties.incrementButtonConfig.enabled == null) {
this.properties.incrementButtonConfig.enabled = false;
}
this.setIncrementEnabled(this.properties.incrementButtonConfig.enabled);
this._incrementEnabled.addEventListener('click', this._incrementButtonProperties.incrementSelectCallback, false);
and the CSS:
.SchedMainCtrlIncrementBtn_En {
position: absolute;
top: 3px;
left: 240px;
display: inline-block;
font-size: 28px;
vertical-align: middle;
width: 35px;
height: 65px;
height: 35px;
background: url("../../../images/icons/IcnListAddRecipient_En.png") no-repeat center;
}
something like this:
var divs = document.querySelectorAll( 'div.yourclass' );
for( var i=0; i < divs.length; i++ ){
divs[ i ].addEventListener( 'eventname', callback, false );
}
EDIT:
From reading your code with this very long variable names I conclude that you want to do something like this:
this.element = document.createElement( 'div' );
this.element.className = 'someName';
this.parentElement.appendChild( this.element );
this.element.addEventListener( 'click', callback, false );
So if this.parentElement is not defined, or if callback is not defined it wont work. I do not know how you coded the class, but all used functions (document.createElement, appendChild, addEventListener) are native functions, so they work.
If possible try to use Jquery it will be simpler you can this $('.class').click(function(){})

Categories

Resources