Why ican't it find the display property? (more below) - javascript

I added a event listener to a button, which would show the css of the #popUpForm, however on the console it logs nothing.
markup:
<input id = "addItem" type = button value = "+">
<div id = "popUpForm">
/* lot of divs*/
</div>
script:
const addBtn = document.querySelector('#addItem')
addBtn.addEventListener('click', function(){
console.log(document.querySelector('#popUpForm').style.display)
})
css:
#popUpForm{
width: 350px;
height: 500px;
display:none; <-- looking for this
}
I'm using webpack, is it possible, that somehow it messes up my code? Any help appreciated!

element.stylerefers to inline styles only.
To check for currently applied styles regardless of the source, use
window.getComputedStyle(document.querySelector('#popUpForm')).display
instead. Beware that this a very expensive call performance-wise, so only ever use it when no better solution is available.
That being said, I'd suggest working with the API for the job, which is the hidden API, which would simplify the check for visibility to
document.querySelector('#popUpForm').hidden
Especially, this makes it very easy to toggle visibility:
document.querySelector('#popUpForm').hidden = !document.querySelector('#popUpForm').hidden

Related

How can I write the javascript script to modify this css file?

Directory Structure:
index.html
--admin
----suit.css
And the part of the css file is:
#suit-left{width:200px;right:240px;margin-left:-100%}
.suit-columns{padding-left:200px;padding-right:40px;}
I want to write a javascript code in the index.html:
<button onclick="">Change CSS</button>
to change the css file like this:
#suit-left { display: none; }
.suit-columns { padding-left: 0; }
How can I do this?regards,thanks a lot
If you want the apply css on particular element by javascript, do something like this.
<button onclick="changeCss()">Change CSS</button>
UPDATE
<script>
function changeCss(){
var suitInput = document.getElementById('suit-left');
suitInput.style.display = 'none';
//UPDATED the answer
var siteCol = document.getElementsByClassName('suit-columns')[0];
siteCol.style.paddingLeft = '0';
//siteCol.style.paddingRight = '0'; //incase of want padding right 0
}
</script>
What I would recommend here is to manipulate the classes associated with the element rather than changing the class definition itself.
Here is a simple example:
.sideBar{ /* your normal rules here */ }
.sideBar.hidden { display:none; }
In order to hide your sidebar, all you'd have to do is add the hidden class name to the element.
In this way, you would define CSS rules for your sidebar when it is open, and different rules for when it is closed. Once you have those two states pre-defined, all you'll have to do is change/add/remove the class to hide/display your sidebar.
I feel like this was the main issue with your question here. The other tasks you wish to perform such as clicking on a button or actually manipulating the class attribute has been covered in many posts already. Here are some useful links for you -
Add class to given element
Using an HTML button to call a JS function
You can write the script in this way and paste below script at head block of index.html
I assume that you have knowledge of jquery.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
function ChangeCss(){
$('#suit-left').css('display','none');
$('.suit-columns').css('padding-left','0');
}
<script>
<button onclick="ChangeCss();" >
Now it will help!
So basically using css function of jquery you can change css/style attributes.
I hope it will help you.

Get CSS styles of an element

I have an element that has the following styles:
<div id="myElement" style="opacity: 0.9; cursor: auto; visibility: visible;"></div>
I want to make sure it always (setInterval?) has these styles, no more no less, NO changes at all. I wonder if its possible to retrive all styles of an element (inline CSS or external) and compare compare them to make sure there were not changes?
For a single element I would not imagine that the performance difference between setting it and checking it first is significant. You might as well just do something like this:
$(document).ready(function(){
var t = setInterval(function(){
$('#myElement').attr('style', 'opacity: 0.9; cursor: auto; visibility: visible;');
}, 1000);
}
I realise that you would normally set the styles using $('#myElement').css, but as you want to ensure no new styles were added, setting the style attribute should achieve what you want. Unfortunately it doesn't account for changes to the stylesheet or style blocks elsewhere on the page. To do this you would have to make your style attribute a bit more comprehensive and include "!important" after each value.
Out of interest, why do you need to do this? It sounds like there might be a better solution to the problem.
Edit:
If you want to stop the user using clearInterval, instead of
var t = setInterval(...);
Just use
setInterval(...);
As clearInterval requires the reference to the interval in order to clear it (correct me if I'm wrong here). By not creating that reference the interval is still executed but not clearable.
Ultimately though I don't think there will be a fool proof method to achieve this. It should however, prevent all but the most determined users with from hiding whatever it is you want them to see.
Edit 2:
If you just want to check the CSS it is possible but a bit of a pain as you would have to check each property in turn. Using jQuery's css function you could do something like this:
$(document).ready(function(){
setInterval(function(){
var el = $('#myElement');
var tampered = false;
if (el.css('display') != 'block') tampered = true;
if (el.css('visibility') != 'visible') tampered = true;
if (el.css('position') != 'static') tampered = true;
....
if (tampered){
// Do your thing
}
}, 1000);
}

Master element attribute? (or technique)

Is there any way you can set an element to be a master and have all other elements on a page appear and behave in exactly the same, same style, same code, same attributes, same values?
<input id="btnBack" name="btnBack" type="button" value="Back" disabled="disabled" style="margin-right: 10px" />
$('#btnBack').click(...do stuff);
<input master="btnBack" />
Or failing this is there any technique to concisely achieve the same result?
I'm half expecting there to be a Javascript library out there that copies all the attributes.
Same style = css
Same attributes, values, etc = JS
See this fiddle for an example to get you started or this code snippet...
The CSS
input {
width: 200px;
background-color: yellow;
}
The JS
var value = 'myval';
var disabled = 'disabled';
var myElements = document.getElementsByTagName('input');
for(var i = 0; i < myElements.length; i++){
myElements[i].value = value;
myElements[i].disabled = disabled;
}
Yes with CSS classes. Create a master class and then use the class="master" on all your elements.
However I think you'll find you don't really want to do this once you get into it. But it will be easy to change the class on the elements you want to change so it won't hurt you to get started this way.
You can read about CSS here: http://www.w3schools.com/css/ though there are better resources w3schools covers a lot of ground.
If you're interested in building a consistent feel to a site and don't mind using jquery (which I love!) then you should checkout the jquery UI themeroller:
http://jqueryui.com/themeroller/
I don't know if this is what you're referring to, but best bet is use a class on all the elements you want to style and behave the same.
E.g.
File: index.html
Awesome Link
<button class="master-class">Awesome Button</a>
File: style.css
.master-class {
color: black;
background: white;
more of your styles...
}
File: scripts.js
$(function() {
$(".master-class").click(function() {
alert("This is from one of the many elements with the class 'master-class'");
});
});
Team Treehouse is a great place to really learn all about everything web. I've been using them for a while even though I knew most of the stuff on there, but I always pick up a few new things. http://teamtreehouse.com/
W3Schools ( http://www.w3schools.com ) is also great. It's where I learnt a lot of stuff in the beginning.
There is also a large amount of podcasts and vodcasts out there to teach you too, just search iTunes for web design.

Can't change background of div region using javascript?

This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}

How to check if a css rule exists

I need to check if a CSS rule exists because I want to issue some warnings if a CSS file is not included.
What is the best way of doing this?
I could filter through window.document.styleSheets.cssRules, but I'm not sure how cross-browser this is (plus I notice on Stack Overflow that object is null for styleSheet[0]).
I would also like to keep dependencies to a minimum.
Is there a straightforward way to do this? Do I just have to create matching elements and test the effects?
Edit: If not, what are the cross-browser concerns of checking window.document.styleSheets?
I don't know if this is an option for you, but if it's a single file you want to check, then you can write your error message and toggle the style to hide it in that file.
<span class="include_error">Error: CSS was not included!</span>
CSS file:
.include_error {
display: none;
visibility: hidden;
}
I test for proper CSS installation using javascript.
I have a CSS rule in my stylesheet that sets a particular id to position: absolute.
#testObject {position: absolute;}
I then programmatically create a temporary div with visibility: hidden with that ID and get the computed style position. If it's not absolute, then the desired CSS is not installed.
If you can't put your own rule in the style sheet, then you can identify one or more rules that you think are representative of the stylesheet and not likely to change and design a temporary object that should get those rules and test for their existence that way.
Or, lastly, you could try to enumerate all the external style sheets and look for a particular filename that is included.
The point here is that if you want to see if an external style sheet is included, you have to pick something about that style sheet that you can look for (filename or some rule in it or some effect it causes).
Here is what I got that works. It's similar to the answers by #Smamatti and #jfriend00 but more fleshed out. I really wish there was a way to test for rules directly but oh well.
CSS:
.my-css-loaded-marker {
z-index: -98256; /*just a random number*/
}
JS:
$(function () { //Must run on jq ready or $('body') might not exist
var dummyElement = $('<p>')
.hide().css({height: 0, width: 0})
.addClass("my-css-loaded-marker")
.appendTo("body"); //Works without this on firefox for some reason
if (dummyElement.css("z-index") != -98256 && console && console.error) {
console.error("Could not find my-app.css styles. Application requires my-app.css to be loaded in order to function properly");
}
dummyElement.remove();
});
I would use a css selector like this from within your jquery widget.
$('link[href$="my-app.css"]')
If you get a result back it means there is a link element that has a href ending with "my-app.css"
Next use this function to validate a specific css property on an element you are depending on. I would suggest something specific to you styles like the width of a container rather something random like -9999 zindex
var getStyle = function(el, styleProp) {
var x = !!el.nodeType ? el : document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
return y;
}
Like this
getStyle($('#stats-container')[0], "width")
or
getStyle("stats-container", "width")
If you are worried about not being able to edit other people's stylesheets, you can proxy them through a stylesheet of your own, using import
#import url('http://his-stylesheet.css');
.hideErrorMessage{ ... }
This is enough if you just want to know if your code is trying to load the stylesheet but won't help if you need to know if the foreign stylesheet was then loaded correctly.

Categories

Resources