JavaScript retrieving element's CSS values - javascript

I'm currently making a basic drag and drop system and need to retrieve the top and left properties of the element being moved. If I do this:
var mover = document.getElementById('mover');
alert(mover.style.top);
Will alert nothing ( ' ' )
Is there any way of retrieving CSS values (in JS) without having to define them with JS first?

You will need to use getComputedStyle if you wish to retrieve properties that are computed rather than defined.
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
FROM the MDN link...
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>

You can get the position of the element as position().top, The css values can be retrieved as .css("margin-top") or .css("top")
alert($('#mover').position().top);
alert($('#mover').css("margin-top"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='mover'>dasdasD</div>
Since you dislike jQuery, here is the solution in pure JS
Update :
var mover = document.getElementById('mover');
alert(window.getComputedStyle(mover).getPropertyValue('margin-top'));
<div id='mover'>dasdasD</div>

There are three possible tops to worry about:
The actual top position. Every element has a top resulting from the page layout, whether or not it has a computed value for the top property. Get this with getBoundingClientRect.
The computed value of the CSS property top. Get this with getComputedStyle, as mentioned in other answers
The current style value set on the element for top. Get this with elt.style.top as you attempted.

var mover = document.getElementById('mover');
alert(mover.offsetTop);
alert(mover.offsetLeft);

Related

Document.querySelector returns a NULL value - script is at bottom of page

I am trying to get the patientNumber (ClinicA100-PF-TR1-P1) using querySelector. I keep getting a NULL value. The patientNumber is at the top of the page and the script is at the bottom. Even after the page is loaded, I click a button that runs the function and it still returns a NULL value.
Here is a screenshot of the selectors (https://recordit.co/IypXuuXib0)
<script type="text/javascript">
function getPatientNumber(){
var patientNumber = document.querySelector("patientNumber");
console.log(patientNumber);
console.log("hello");
return patientNumber;
}
var patientNumber = getPatientNumber();
console.log(patientNumber);
_kmq.push(['identify', patientNumber]);
</script>
Thank you for any help you can provide.
ADDITIONAL HTML INFORMATION:
I am using Caspio (database management software) to create this HTML code. I don't know if that may be the cause of the issue. Here is the HTML CODE.
<p class="sponsorName" id="sponsorNameID">[#authfield:User_List_Sponsor_Name]</p>
<p class="clinicNumber" id="clinicNumberID">[#authfield:User_List_Site_Number]</p>
<p class="protocolNumber" id="protocolNumberID">[#authfield:User_List_Protocol_Number]</p>
<p class="patientNumber" id="patientNumberID">[#authfield:User_List_Patient_Number]</p>
You are missing a dot.
var patientNumberNode = document.querySelector(".patientNumber");
var patientNumber = patientNumberNode.innerText;
if you select the item with class".", if you select with id, you should use"#".
var patientNumber = document.querySelector(".patientNumber"); // class select
var patientNumber = document.querySelector("#patientNumber"); // id select
Your selector is incorrect. It should be
var patientNumber = document.querySelector(".patientNumber");
Why is it failing:
When you use patientNumber as the selector, JavaScript looks for an element with a name of patientNumber. Since that's not the case, and you are looking for an element with a class of patientNumber, you need to use the . notation.
Addon Suggestion (can be ignored):
Since you are also using IDs, consider using document.getElementById() as it is faster than using document.querySelector().
Note that if you use document.getElementById(), your .patientNumber selector won't work. You need to write it as
document.getElementById('patientNumberID');
//ID based on the screenshot of the DOM you've shared
While the code is at the bottom of the page, and the element is at the top, it is not loaded asynchronously as it comes from a third party database. i put a delay in the getPatientNumber() and it works now.

Javascript movecontent from one div to another

I have the code that actually works:
<script type="text/javascript">//<![CDATA[
function MoveContent() {
var srcObj = document.getElementById("src");
var destObj = document.getElementById("dest");
destObj.value = srcObj.innerHTML;
}
//]]>
</script>
But I need to move content from 2 divs which isn't possible using this code.
I don't know JavaScript, so what should I add tho this code?
Sorry for bad English, thanks in advance
I suggest you use jQuery library. Have you heard of it?
http://jquery.com/
Simple code to accomplish your goal:
var srcHtml = $('#src').html();
$('#dest').html(srcHtml);
Use:
destObj.innerHTML = srcObj.innerHTML;
value is the value of an input element, innerHTML is the content of a DIV or other element.
Assuming Both are div's rewrite the following line
destObj.value = srcObj.innerHTML;
as
destObj.innerHTML= srcObj.innerHTML;
Since div is not having an attribute value you cannot copy the content to the destination div using value.
Like you get value from one div using
var srcObj = document.getElementById("src");
get another variable like srcObj2 and store the next div. Concatenate values of two variables and set it to the destObj

What is the proper method of creating an object of a parent window using JQuery

I have seen in researching how to create an object of an element's parent window at least two different ways of writing the code to do it using JQuery.
Which one of these are correct, and what is the difference in the first one versus the second one?
The purpose in trying to figure this out is that I want to set the size of an iFrame and position it within the parent window.
Thanks.
Example 1
var windowId = 'custErrWindow';
var parentWindow = $('#' + windowId).parent();
var height = parentWindow.height();
Example 2
var windowId = 'custErrWindow';
var parentWindow = $('#' + windowId).parent.$('#window');
var height = parentWindow.height();
As far as I know there is no .parent property of objects that jQuery returns, but maybe someone with more knowledge can correct me on this -- so that would make your $('#' + windowId).parent undefined. In terms of the right way to find a parent element, check jQuery's docs for parent() vs. parents(); for example, parent() of an HTML tag element will return a set with document, while parents() does not. Hope that helps.

How to get the CSS left-property value of a div using JavaScript

My CSS rule looks like this:
#my-div{
display: none;
position: absolute;
left: -160px;
bottom: -150px;
}
I'm trying to get value of the left-property like this:
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
The problem is that both return null. Where is the problem?
The problem is that someElement.style.left only work if you have inline style. Since you apply your styling through a stylesheet, you will not be able to fetch the value the way you expect.
You have a couple of other approaches you could take to get the value through JavaScript:
window.getComputedStyle:
It is possible to get the computed style of an element using window.getComputedStyle, the problem is that it has quite limited support (IE9+). If you still want to use it you could wrap it up in a function to make it a bit easier to get each property:
function getCssProperty(elmId, property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var left = getCssProperty("my-div", "left");
Working example
jQuery (or some other library):
Another option would be to use a JavaScript library like jQuery (or whatever you prefer), which will provide you with a cross-browser solution to get the value.
With jQuery you could use the .css() method to read the CSS-property of the element.
$(function () {
var left = $("#my-div").css("left");
});
Working example
​
You should call this
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
when document is loaded, if you call it earlier it will return null because element doesnt exists yet. So you can use jQuery to determine when all content is loaded.
$(function() {
//put your code here
});
The problem is that, since CSS is loaded separately from the JS, there's no official way to ensure that the style.left property will be accurate. The style.left property is a different, higher-priority style override.
You'll need to use the getComputedStyle function.
https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle
Ex:
var div = document.getElementById('my-div');
var style = getComputedStyle(div);
var left = style.getPropertyValue("left");
Maybe you have to call your functions after document ready.
If you use jQuery you can find left value faster:
$(document).ready(function() {
var $left = $('#my-div').css('left');
console.log($left);
});

jQuery create element initially hidden

Is there a way to create an element and have it hidden initially? I am creating an iframe but don't want it shown right away.
Very simple. Just do this:
var myFrame = $("<iframe>").hide();
var my_iframe = $('<iframe name="your_iframe" src="your_source"></iframe>');
now my_iframe holds your jQuery created iframe. Modify it, do what you wish and then put it in the dom.
It wont be visible until you insert it into the dom.
Just create it and style it as being hidden, in one of many possible ways, like this:
var secretThing = $('<iframe></iframe>', { css: { 'display': 'none' }});
$('body').append(secretThing);
Another way to make something hidden is to position it far off the viewport, or to put it behind something else, or to set some dimension to zero. It depends on the rest of your design. Personally, I'd be inclined to give the element a class value that makes it hidden.
(#gilly3 wisely notes that the handy jQuery "hide" function might be a simple way to do this.)
var theElement = <create the iframe here>;
theElement.hide();
// append theElement here
Like this:
var FName = $("<iframe>").hide();

Categories