Can't console.log() .style.display information - javascript

I'm able to correct switch between a dropdown menu being displayed and hidden when I click on my input tag, but when console logging the style displayed I get nothing shown on the console. What is the explanation for not being able to see this and how would I go about trying to correctly see which display style I used?
document.getElementById('search').addEventListener("click", function () {
const grid1 = document.querySelector(".modal");
grid1.style.display = grid1.style.display ? "none" : "flex";
console.log(grid1.style.display);
});

Instead of using 'yourelement.style.display' use 'getComputedStyle' function to get the value of any property in this case 'display', thats because Computed style contains all the CSS properties set to an element. Even if do not set a property to an element. You will still find that property in the computed styles.
Modifiying your code with 'getComputerStyle'
document.getElementById('search').addEventListener("click", function () {
const grid1=document.querySelector(".modal")
console.log(window.getComputedStyle(grid1).display)
grid1.style.display = window.getComputedStyle(grid1).display == "none" ? "flex" : "none";
console.log(window.getComputedStyle(grid1).display)
})
.modal {
display: none;
}
<input id="search">
<select class="modal"></select>
For more clarification check Window.getComputedStyle() in MDN Web Docs

Related

Finding width of hidden element similar to jQuery in pure javascript

I am trying to replicate the jQuery width function using pure JavaScript. Pure JavaScript functions such as getComputedStyle or offsetWidth seem to work if the element is visible, but I cannot replicate the same behavior when the element is hidden.
It seems that jQuery is doing something different here and I cannot figure out what exactly.
To clearly explain what i am trying to do, Here is a codepen example where I try the getComputedStyle in comparison with the jQuery width function for calculating the width of a hidden element that is changing dynamically.
const input = $('input');
const sizer = $('.sizer');
const sizerDom = document.querySelector('.sizer');
input.on('input', evt => {
sizer.text(evt.target.value);
console.log(sizer.width())
console.log(getComputedStyle(sizerDom, null).width);
});
.sizer {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text">
<span class="sizer">
https://codepen.io/OmranAbazid/pen/OJNXyoG
That is because in jQuery's internal logic, it interally swaps the display property from none to another value so that it forces the browser to momentarily render it. Otherwise the measurements will always be 0 since the element is never rendered.
Also, instead of trying to use window.getComputedStyle which will return a string value of the CSS dimension (e.g. 100px), you can use sizerDom.getBoundingClientRect() to get the actual number instead (which returns, say, 100) without needing to do additional parsing.
const input = $('input');
const sizer = $('.sizer');
const sizerDom = document.querySelector('.sizer');
input.on('input', evt => {
sizer.text(evt.target.value);
console.log(sizer.width())
const cachedDisplay = window.getComputedStyle(sizerDom).display;
sizerDom.style.display = 'inline-block';
console.log(sizerDom.getBoundingClientRect().width);
sizerDom.style.display = cachedDisplay;
});
.sizer {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text">
<span class="sizer">

Revert `display: none` on elements to original value [duplicate]

This question already has answers here:
how to revert back to normal after display:none for table row
(9 answers)
Closed 4 years ago.
explanation
I have a script that hides elements, if the user does not have the permission to view/use it. I set display: none for those elements.
Now later, when I want to show the elements again, I don't just want to set display: block or something, because maybe the elements original display value was something other than block. Is there a way I can revert the display or set it to a neutral value?
example
E.g. <div class="fancy-class">...</div> If fancy-class has display set to inline-block and I just set it to block with my script, that will break the ui.
attempts
I have tried using display: initial but that resets it to the HTML-element's initial styling - not the class's styling.
I hope I don't have to keep the original values in an array and then apply them again. Doesn't seem nice.
use: element.style.display = "" to reset style.display of an element
(() => {
const displayState = reset =>
Array.from(document.querySelectorAll("div"))
.forEach( el => el.style.display = reset ? "" : "none" );
// ^ restore original display state
document.querySelector("#showAll").addEventListener("click", () => displayState(true));
document.querySelector("#hideAll").addEventListener("click", () => displayState());
})();
#first, #second, #third {
display: inline-block;
margin-right: 1em;
}
<div id="first">[First]</div>
<div id="second">[Second]</div>
<div id="third">[Third]</div>
<button id="showAll">show divs</button>
<button id="hideAll">hide divs</button>
Before setting display to none, you can save it, and apply it back.
var display = document.getElementsByClassName("fancy-class").style.display;
document.getElementById("fancy-class").style.display = none;
Set above saved attribute.
document.getElementById("fancy-class").style.display = display;

Set a css attribute to important through javascript

On my page I want to set the attribute display to block!important when there's a specific string in the url,
I've been doing some research, but can't find the correct answer. Using the code below I can set the background-color: green!important on the body, but I don't know how to target something else (the "loginActive" id element).
:javascript
if(window.location.href.indexOf("sign_up") > -1) {
document.body.style.setProperty ("background-color", "green", "important");
document.getElementById("loginActive").style.display = "block", "important";
}
Any tips on how I can set display: block!important on the element #loginActive ?
Try this
var item = document.getElementById("loginActive");
item.style. display = 'block !important';
Or
item.setAttribute('style', 'display:block !important');
But you shouldn't do that

CKEditor default style for styleCommand (format styles with buttons)

I have created a CKEditor plugin which does the base p, h2, h3, h4 formatting with custom buttons (instead of the stylescombo). It works great, but if I uncheck an element (ex. 'h2'), sets the 'div' tag as parent element for the row. I want to be the 'p' as the default element and also the 'p' button can't be unchecked (unless I clicking on another, ex. 'h2' button). How is this possible?
The plugin looks like:
CKEDITOR.plugins.add('stylesbuttons_custom',{
lang:'en',
icons:'p,h2,h3,h4',
init:function(editor){
var order=0;
var addButtonCommand=function(buttonName,buttonLabel,commandName,styleDefiniton){
if (!styleDefiniton)
return;
var style=new CKEDITOR.style(styleDefiniton);
editor.attachStyleStateChange(style,function(state){
!editor.readOnly && editor.getCommand(commandName).setState(state);
});
editor.addCommand(commandName,new CKEDITOR.styleCommand(style));
if (editor.ui.addButton){
editor.ui.addButton(buttonName,{
label:buttonLabel,
command:commandName,
toolbar:'basicstyles,'+(order+=10)
});
}
};
var lang=editor.lang.stylesbuttons_custom;
addButtonCommand('P',lang.p,'p',{element:'p'});
addButtonCommand('H2',lang.h2,'h2',{element:'h2'});
addButtonCommand('H3',lang.h3,'h3',{element:'h3'});
addButtonCommand('H4',lang.h4,'h4',{element:'h4'});
}
});
I load the plugin like:
config.extraPlugins='stylesbuttons_custom';
I put buttons to toolbar like:
config.toolbar:[['P','H2','H3','H4','Pre']];
Here is a screenshot about the problem:
Cross posting my answer from CKEditor forum.
I think that you need to write your own command instead of using CKEDITOR.styleCommand.
It should work exactly like CKEDITOR.styleCommand when style is not yet applied on current selection.
But when clicked again it should apply the paragraph style, not remove the previously applied style. E.g:
styleCommand.prototype.exec = function( editor ) {
editor.focus();
if ( this.state == CKEDITOR.TRISTATE_OFF )
editor.applyStyle( this.style );
else if ( this.state == CKEDITOR.TRISTATE_ON )
editor.applyStyle( paragraphStyle );
};
PS. I created a ticket: http://dev.ckeditor.com/ticket/10190 because I think that removing block style should revert back to paragraph (in enterMode=P). For now use the above workaround.
Yes, #Reinmar notifies that there is an error in the CKEditor's style.js where the this._.enterMode is not defined.
Doing this on style.js, resolve the problem:
this._ = {
definition: styleDefinition,
enterMode: CKEDITOR.config.enterMode
};
And from now on when a style button is unchecked the block changes to the default 'p' element.
Now my complete working plugin looks like:
(function(){
CKEDITOR.plugins.add('custombuttons',{
lang:'hu,en,de,ro',
init:function(editor){
var order=0,t=this,lang=editor.lang.custombuttons;
// addButtonCommand helper
var addButtonCommand=function(buttonName,buttonLabel,commandName,styleDefiniton){
var style=new CKEDITOR.style(styleDefiniton);
var styleCommand=function(style){
this.style=style;
this.allowedContent=style;
this.requiredContent=style;
this.contextSensitive=true;
};
styleCommand.prototype={
exec:function(editor){
editor.focus();
if (this.state==CKEDITOR.TRISTATE_OFF)
editor.applyStyle(this.style);
else if (this.state==CKEDITOR.TRISTATE_ON)
editor.removeStyle(this.style);
if(commandName!='fakecommand'){editor.execCommand('fakecommand');editor.execCommand('fakecommand');} /* hack to change button state properly */
},
refresh:function(editor,path){
this.setState(path&&this.style.checkApplicable(path)?(this.style.checkActive(path)?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF):CKEDITOR.TRISTATE_DISABLED);
}
};
editor.addCommand(commandName,new styleCommand(style));
if(editor.ui.addButton){editor.ui.addButton(buttonName,{label:buttonLabel,command:commandName,toolbar:'basicstyles,'+(order+=10),icon:t.path+'images/'+commandName+'.png'});}
};
// _fakebutton (hack)
addButtonCommand('_fakebutton','','fakecommand',{element:'span'});
// style buttons
addButtonCommand('P',lang.p,'p',{element:'p'});
addButtonCommand('H2',lang.h2,'h2',{element:'h2'});
addButtonCommand('H3',lang.h3,'h3',{element:'h3'});
addButtonCommand('H4',lang.h4,'h4',{element:'h4'});
addButtonCommand('Pre',lang.pre,'pre',{element:'pre'});
addButtonCommand('Mini',lang.mini,'mini',{element:'p',attributes:{class:'mini'}});
addButtonCommand('Important',lang.important,'important',{element:'span',attributes:{class:'important'}});
addButtonCommand('Comment',lang.comment,'comment',{element:'span',attributes:{class:'comment'}});
addButtonCommand('Mark',lang.mark,'mark',{element:'mark'});
addButtonCommand('ImgLeft',lang.imgLeft,'imgLeft',{element:'img',attributes:{class:'imgleft'}});
addButtonCommand('ImgRight',lang.imgRight,'imgRight',{element:'img',attributes:{class:'imgright'}});
addButtonCommand('ImgCenter',lang.imgCenter,'imgCenter',{element:'img',attributes:{class:'imgcenter'}});
// button shortcut keys
editor.setKeystroke(
[
[CKEDITOR.CTRL+48,'p'], // Ctrl+0
[CKEDITOR.CTRL+49,'h2'], // Ctrl+1
[CKEDITOR.CTRL+50,'h3'], // Ctrl+2
[CKEDITOR.CTRL+51,'h4'], // Ctrl+3
]);
}
});
})();
There is still a hack in the code. I needed to run a 'fakecommand' to really update (refilter?) the changed tags and all its parent tags. For example the 'p.mini' button caused problems (the state was not updated) when clicked multiple time. So there is still an unelegant solution. Any idea how to force to update or refilter the code after a style is applied?

Javascript only recognizising inline style and not style set in head

I have simple JS function that toggles the DISPLAY of a DIV. The DIV display is set to 'none' by default. If I use an inline style to set the display, it works fine, but if I set the style in the head it only works after I run the function the second time. So it only sees that the display is set to none after the display is set in the function. It doesn't recognize that it is set in the CSS in the head. If I use an inline style, it works fine.
Also, if I change my conditional statement from:
if (OBJ.style.display == 'none')
to
if (OBJ.style.display = 'none')
Use window.getCurrentStyle or element.currentStyle in order to obtain style from the head or body. They're supported by different browsers so here's a cross-browser example:
function getStyle( elem, style ) {
var a = window.getComputedStyle,
b = elem.currentStyle;
if ( a ) return a( elem ).getPropertyValue( style );
else if ( b ) return b[ style ];
}
getStyle( document.getElementById('OBJ'), 'display' )
The style property of an element only contains the inline style, not inherited styles or styles from a style sheet.
You can use the offsetHeight property to check if the element has any size, as it is zero when the element is not visible.
if (OBJ.offsetHeight == 0) ...
Another suggestion is to use css classes:
css:
.hide{
display:none;
}
html:
<div id="mydiv" class="hide">hello world</div>
<button onclick="toggle();">toggle</button>
js:
function toggle(){
var obj = document.getElementById('mydiv');
if(obj.className == 'hide')
obj.className = '';
else
obj.className = 'hide'
}
http://jsfiddle.net/XBhMA/1/
Note this will only work if the element contains only one class. If it contains more, you will need to modify.

Categories

Resources