Displaying element's layer style in javascript - javascript

I am trying to display a div's layer style using javascript. My js code is as follows:
<body>
<script>
function displayStyle(objectId,styleName){
var objRef=document.getElementById(objectId);
var styleValue=eval(objRef.style + styleName);
window.alert(styleName +" =" +styleValue);
}
</script>
<div id="myObject" style="position: absolute; left:50px; top: 200px; background-color: #cccccc;">My Object</div>
<form>
style:<input type="text" name="styleText">
<input type="button" value="Display Style"
onClick="displayStyle('myObject',this.form.styleText.value);">
</form>
</body>
The problem is on the button click, the style property doesnot pop up in window alert.The console shows the
Uncaught SyntaxError: Unexpected identifier
Plz help.

You should use the bracket notation
function displayStyle(objectId, styleName) {
var objRef = document.getElementById(objectId);
var styleValue = objRef.style[styleName];
window.alert(styleName + " =" + styleValue);
}

I really do not recommend using eval();
The other problem is you are missing a dot in the line.
var styleValue = eval(objRef.style + '.' + styleName);
But this will only work assuming you are passing a valid style property name through also. I would try using one of the approaches below.
If you want to get to one of the style attributes property values you can simple use.
function displayStyle(objectId, styleName) {
var objRef = document.getElementById(objectId),
styleValue = objRef.style.getPropertyValue(styleName);
window.alert(styleName +" = " +styleValue);
}
Another way is to use the square bracket syntax.
In JS you can access the inner properties in an Object with a . like most C based languages. But they also give you a string based accessor.
var person = {
name: 'Rick'
}
console.log(person.name); //Rick
console.log(person['name']); //Rick
This system works on any object in JS.
However using this on a Style object may result in different property names being used.
E.G in HTML style attributes you use margin-left. If you want this value using the square brackets you have to use style['marginLeft'];
If want to get all the style properties that have been rendered on the object you can also use.
window.getComputedStyle(objRef);
Which returns you an object of style properties, but with calculated heights etc. But it does not work in older browsers.
Sorry if this is not clear I typed it out on my phone.

Related

Template Literals How To Make a ?Universal Rule?

I'm new to coding but I am using template literals in a project using css variables. this example sets all the variables in one shot inside a function. this is referring to inputs which all have an eventlistener on them.
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
I want to set another rule for a span to display the values. right now I am doing each one individually like this.
heightDisplay.innerHTML = height.value + 'px';
widthDisplay.innerHTML = width.value + 'px';
all the span's ids will be " this.name + 'Display' "
I want to right a rule that sets them all at once using the literals(similar to the rule that sets the variables) instead of writing 30 lines of code.
I can't figure out the syntax to add Display on there and i don't know where to put the back ticks.
I assume this is possible, since pretty much everything in Javascript is.
Thanks for your time.
I assume that you have an iteration where this Code-Line is Executed:document.documentElement.style.setProperty(--${this.name}, this.value + suffix);
In this Iteration you can set the Values of your spans like this:
var Span = document.querySelector(`[id*= ${this.name}]`);
Span.innerHTML = this.value+ "px";
Edit:
The querySelector - function gets a css-selector as a parameter. the [] - Brackets is a css selector that gets an element with an atribute (in this case id) and a value (this.name). The *= between them means, that you can select an element that has a substring in the value of the atribute.

How can I set attribute which ends with dollar sign using Javascript?

I'm trying to create a pre-processor that converts some custom markup in a file into attribute names which works with Polymer's data binding $= annotation, however I've come across a stumbling block.
I cannot set attributes using Javascript that contain a dollar sign.
I'm trying to convert
<p stuff="align bottom#md top#lg; offset 2gu#md; "></p>
to
<p align-bottom$="{{globals.abovemd}}" align-top$="{{globals.abovelg}}" offset-2gu$="{{globals.abovemd}}">
I have tried:
.setAttribute("align-bottom$", "{{globals.abovemd}}");
But it won't work because the attribute name cannot contain a dollar sign.
Can any one think of a way I can get around this?
This might do the trick(setting invalid attribute names), although obviously not valid in all cases:
function setDollar(el,name,val){
var attrs = [];
var tagName = el.tagName;
for (var i = 0; i < el.attributes.length; i++) {
var attrib = el.attributes[i];
if (attrib.specified) attrs.push(attrib.name+'="'+attrib.value+'"')
}
el.outerHTML = '<'+tagName+ ' '+name+'$="'+val+'"'+attrs.join(' ')+'>'+ el.innerHTML+'</'+el.tagName+'>';
attrs.forEach((attr)=>el.setAttribute(attr.name, attr.value))
}
setDollar(document.querySelector('#wow'),'foo','bar')
<div id="wow"><p>something</p></div>
Still, needs checking for closing tag etc.
Just exclude the $ anytime you are dealing with that property. The $ is just reflecting the property to the attribute onto that DOM element.
.setAttribute("align-bottom", globals.abovemd);
Pretty sure this gonna work
(you need put align-bottom$="" into your html first, this is just to update the value):
.attributes['align-bottom$'].value = "{{globals.abovemd}}";

Extract property of a tag in HTML using Javascript

Is it possible to extract properties of a HTML tag using Javascript.
For example, I want to know the values present inside with the <div> which has align = "center".
<div align="center">Hello</div>
What I know is:
var division=document.querySelectorAll("div");
but it selects the elements between <div> & </div> and not the properties inside it.
I want to use this in the Greasemonkey script where I can check for some malicious properties of a tag in a website using Javascript.
Hope I'm clear..!!
You are looking for the getAttribute function. Which is accessible though the element.
You would use it like this.
var division = document.querySelectorAll('div')
for(var i=0,length=division.length;i < length;i++)
{
var element = division[i];
var alignData = division.getAttribute('align'); //alignData = center
if(alignData === 'center')
{
console.log('Data Found!');
}
}
If you're looking to see what attributes are available on the element, these are available though
division.attributes
MDN Attributes
So for instance in your example if you wanted to see if an align property was available you could write this.
//Test to see if attribute exists on element
if(division.attributes.hasOwnProperty('align'))
{
//It does!
}
var test = document.querySelectorAll('div[align="center"]');

.addClass() not working

This is my first time working with .addClass().
In my project, I need to display notifications on a dummy phone screen (an image of iPhone). A notification has a title and some description. This title and description is coming from a form on the same webpage. To compose this notification, I am doing:
var notificationText = $('#title').val().addClass('title') + plainText.addClass("description");
However, I am getting an error:
TypeError: $(...).val(...).addClass is not a function
What am I doing wrong here?
UPDATE:
So, as per the overwhelming requests, I did:
var notificationText = $('#title').addClass('title').val() + plainText.addClass("description");
However, I am getting an error:
Uncaught TypeError: Object sss has no method 'addClass'
jsFiddle
UPDATE 2: I do not need to style the description, so I removed the class related to it. Please see my updated fiddle. Now the problem is that the text in title is getting bold instead of the one copied in #notifications. It is not getting styled as per the CSS.
So many answers in so little time... sigh
I gathered what I think you wanted. Try this one:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7b3j2/13/
$(document).ready(function(){
CKEDITOR.replace( 'description' );
$('#title').focus();
$('form').submit(function(event){
event.preventDefault();
var html=CKEDITOR.instances.description.getSnapshot();
var divEle=document.createElement("DIV");
divEle.innerHTML=html;
var plainText=(divEle.textContent || divEle.innerText);
var $title = $('<span></span');
$title.addClass('title');
$title.text($('#title').val());
var $desc = $('<span></span');
$desc.addClass('description');
$desc.text(plainText);
$('form').append($title);
$('form').append($desc);
});
});
You can obviously chain some of the span operations, but I left them readable for now. Shorter version would look like:
var $title = $('<span></span').addClass('title').text($('#title').val());
var $desc = $('<span></span').addClass('description').text(plainText);
$('form').append($title).append($desc);
As you probably know by now, but for completeness, the initial errors were the result of trying to apply jQuery methods to string objects. This solution creates new jQuery span objects that can then be styled and appended to the form.
You are trying add class to a value, which is definitely is not a jQuery object
Try this instead:
$('#title').addClass('title').val()
addClass can only be performed on jQuery objects and returns a jQuery object - that's what makes it chainable. You can't add a class to a string.
So, in this code, there are actually two mistakes:
1) plainText.addClass - plainText is a string, and not a jQuery object. You must add the class to the element you created (in your case, the divEle element), but, since addClass only works with jQuery objects, you must convert your div to a jQuery element first. You can accomplish this by doing the following:
$(divEle).addClass('description');
2) addClass returns a jQuery object, so you can't concatenate it with a string.
EDIT: Just realized that you're appending notificationText (which is a string) to the DOM. You must convert it to a div and add the div to the DOM.
jsFiddle: http://jsfiddle.net/7b3j2/17/
Mistake done by you:
<div id="title"><div>
$('#title').val().addClass('title')
->Now here $('#title').val() will give that particular element value.
->$('#title').val().addClass() you are adding class to that value.
Use this:
$('#title').addClass();
As you cannot add class to element's value.
You should addClass to particular element as addClass internally will add attribute class to that element.
So finally solution becomes:
$('#title').addClass('title').val()
For adding a class, you have to use
$('#title').addClass('title');
If you want to get the value, you can use
$('#title').addClass('title').val()
While addClass and val() are both methods on the jQuery object, val() is not chainable like addClass is. When you do $('#title').val() you aren't returning the object, you're only returning the string value of the element.
Use this instead:
$('#title').addClass('title');
And if you still need to get the value:
$('#title').addClass('title').val();
The reason why plaintext is producing an error is because you're trying to use the jQuery addClass method on a DOM node that has been natively created with document.createElement("DIV");. This will not work. To get it to work you either need to to define your new element with jQuery:
var divEle = $('<div></div>');
and then add the class:
divEle.addClass('description');
Or use the native classname method to add the class to the DOM node:
divEle.className = divEle.className + " description";
Try putting addClass first
$('#title').addClass('title');
Update
To get the code fully working you should split up the line like so.
var notificationText = $('#title').val() + ' ' + plainText;
$('#title').addClass('title');
$(plainText).addClass("description");
Fiddle
Final Update
So what we actually want to do here is:
get the values of the content
append them on submit and style the appended text
Example
// Get the text.
var notificationText = $('#title').val() + ' ' + plainText;
// Append to form.
$('form').append('<span class="summary">' + notificationText + '</span>');
// CSS styling
.summary {
display:block;
font-weight: bold;
}
See Fiddle
Considering #title is the id of the element.
You can directly need to add classname to it.
$('#title').addClass('className');
where className is the name of the class.
because you are trying to add class over value instead of element.
$('#title').val().addClass('title') //it is wrong
replace it with:
$('#title').addClass('title')
if plainText is not an element object you initialize by
var plainText = $('#anotherId');
will also cause this error.

Why does this javascript throw this particular error?

In my HTML code I have a button that when pressed runs a javascript function. This is the HTML code for the button:
<button type="button" onclick="repeatName()">Click me!</button>
I want the user to enter something into a text field (which is inside of a form). This is the code for the text field:
<input type="text" name="txtName" />
I want this div's innerHTML to be changed according to the information put in the name textbox once the button is pressed. This is the code for the div:
<div name="editThis" width="50px" height="50px" border="1px">
</div>
When the button is clicked, I want it to run the function below. It is supposed to change the innerHTML of the div.
function repeatName() {
var editField = document.getElementsByName("editThis").innerHTML;
var repeatedName = document.theForm.txtName.value;
editField = (repeatedName + " is the value.")
}
THE PROBLEM IS that whenever the button is clicked, I see this error in the Firefox error console:
Error: uncaught exception: [Exception... "Cannot modify properties of a WrappedNative" nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)" location: "JS frame :: chrome://global/content/bindings/autocomplete.xml :: onxblpopuphiding :: line 825" data: no]
What is this error and how can I correct it?
According to the documentation, document.getElementsByName(str) returns "a list of elements".
It's clear that "a list of elements" doesn't have a singular .innerHTML property. I'd guess that the specific error relates to your browser's internal mechanism for representing that list in its own WrappedNative type.
Iterate the results instead; in your case, you only need the first result, so get it with the array accessor syntax [0].
But, since name properties relate to form components, you should use id instead. Retrieving an element by ID is easier, since IDs are [supposed to be] unique.
Also, since Javascript has no references, you cannot store innerHTML in a variable and change it expecting the original property to change; you must make the assignment in the same statement in which you notate innerHTML:
function repeatName() {
var editField = document.getElementsById("editField");
var repeatedName = document.theForm.txtName.value;
editField.innerHTML = repeatedName + " is the value."
}
I think Tomalak has it right. Alternately, you can give your div an id, and then use getElementById, which will return a single object and not a collection.
i.e.
<div id="editThis" .... > .... </div>
...
...
document.getElementById("editThis").innerHTML = repeatedName + " is the value";
Div elements don't have a name attribute, so use an id instead.
<div id="editThis" ...>
Then use:
function repeatName() {
var editField = document.getElementById("editThis");
if (editField) {
editField.innerHTML = document.theForm.txtName.value + ' is the value';
}
}

Categories