Partly editing inline style attribute of an element - javascript

It's currently working like such:
var ball = document.getElementById('ball');
//some code
let bml = parseInt(ball.style.marginLeft,10);
//if *conditional statement* is true, do:
ball.setAttribute("style","margin-left:"+(bml-4)+"px;");
But I'm trying to achieve it by writing this:
ball.style['marginLeft']=bml-4;
except the result isn't the same.
I've seen online examples of using this method to edit attribute values dynamically but they always seemed to use pre-calculated values like "400px" and never variables like my example, why is that?

Style properties must be set with string values, as it is documented in the following link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style#setting_styles
So it is possible to dynamically set style values by using String Literals:
ball.style['marginLeft']=`${bml-4}px`;

Related

Render JavaScript variable in HTML as part of a Liquid template

I would like to read a query string in JavaScript, and then modify the link that will be rendered in HTML, however I am rendering the HTML as part of liquid loop. So am not sure how I would read the query string in JavaScript, store the value of query string in a variable, and show it in the html that's rendered as part of a liquid loop.
I am still new to Liquid so any help would be appreciated. I am using this as part of Dynamics 365 portals.
If I understand correctly you could just use javascript to make an html element then edit that element as you wish in javascript via
var x = document.getElementById("myVar");
//Use var x to edit this element here
//OR
var x = document.createElement("myVar");
//Use var x to edit this element here
document.getElementByID is only used if your element is already made in html, where document.createElement is used if you'd like to make a new element rather than using one thats already made.

Can I use javascript to add or remove attributes from a Video tag?

I don't know JavaScript and I want to add some attributes to a video tag.
Is it possible to use JS code that can affect all the videos on one page?
Please see the below code I tried this after some online search not sure if it is correct or not!
I appreciate your help.
function playVideo() {
var elementVar = document.getElementsByTagName("video");
elementVar.setAttribute("autoplay: autoplay" || "loop: loop" || "controls: false") ;
}
You can definitely set attributes on an element with Javascript. However, the setAttribute function needs to be used differently. It takes two arguments:
The name of the attribute
The value for that attribute
So in your case this would be a correct way to set the autoplay attribute:
elementVar.setAttribute("autoplay","autoplay")
Also, I'm not sure what does the or operator (||) is supposed to be doing between the strings. But it looks like you want to set all of those attributes. That needs to be done with 3 calls, like this:
elementVar.setAttribute("autoplay","autoplay")
elementVar.setAttribute("loop","loop")
elementVar.setAttribute("controls","false")
You can definitely use javascript to add attributes to a video tag, but you aren't using the proper syntax.
The proper syntax for setAttribute is:
.setAttribute(attrName, attrValue);
Note that it can also only set one attribute at a time, so you can't do "autoplay: autoplay" || "loop: loop".
Here's the code you probably want:
function playVideo() {
var elementVar = document.getElementsByTagName("video");
elementVar.setAttribute("autoplay", "autoplay");
elementVar.setAttribute("loop", "loop");
elementVar.setAttribute("controls", "false");
}

Error:Error response status: 13 when calling waitForCondition

I am trying to write a browser test using selenium-webdriverjs. When I call the following code snippet, I get Error:Error response: 13.
browser.waitForCondition('var element = document.querySelector(".selector"); var style = document.defaultView.getComputedStyle(element,null); style =' + btnColor ,timeout);
I am waiting for a condition which I would like to get a computed css style from an element obtained from a css selector. Then the computed css style is compared to a variable called btnColor. (I know that it is also possible to do the same thing using a Webdriver JS API method called getComputedCss. However, I am interested in using waitForCondition to achieve the same purpose.)
I would like to know how to properly use waitForCondition to achieve what I want to do as said above and why the code snippet is throwing the error.
Thanks in advance!
I have found my answer to this question.I have made several javascript mistakes in the expression. The following is the code snippet I have used to solve my problem.
browser.waitForCondition('var element = window.document.querySelector(".selector"); var style = window.document.defaultView.getComputedStyle(element,null).getPropertyValue("background-color"); style ="' + btnColor + '"',timeout);
1) In order to use document, you need to call the window object first.
2) In order to get the computed background-color, I need to use the method .getPropertyValue().
3) btnColor contains a string. Therefore I need to put a double-quotation around it for the interpreter to recognize it as a string.

Adding Javascript variables to HTML elements

So, I have some code that should do four things:
remove the ".mp4" extension from every title
change my video category
put the same description in all of the videos
put the same keywords in all of the videos
Note: All of this would be done on the YouTube upload page. I'm using Greasemonkey in Mozilla Firefox.
I wrote this, but my question is: how do I change the HTML title in the actual HTML page to the new title (which is a Javascript variable)?
This is my code:
function remove_mp4()
{
var title = document.getElementsByName("title").value;
var new_title = title.replace(title.match(".mp4"), "");
}
function add_description()
{
var description = document.getElementsByName("description").value;
var new_description = "Subscribe."
}
function add_keywords()
{
var keywords = document.getElementsByName("keywords").value;
var new_keywords = prompt("Enter keywords.", "");
}
function change_category()
{
var category = document.getElementsByName("category").value;
var new_category = "<option value="27">Education</option>"
}
remove_mp4();
add_description();
add_keywords();
change_category();
Note: If you see any mistakes in the JavaScript code, please let me know.
Note 2: If you wonder why I stored the current HTML values in variables, that's because I think I will have to use them in order to replace HTML values (I may be wrong).
A lot of things have been covered already, but still i would like to remind you that if you are looking for cross browser compatibility innerHTML won't be enough, as you may need innerText too or textContent to tackle some old versions of IE or even using some other way to modify the content of an element.
As a side note innerHTML is considered from a great majority of people as deprecated though some others still use it. (i'm not here to debate about is it good or not to use it but this is just a little remark for you to checkabout)
Regarding remarks, i would suggest minimizing the number of functions you create by creating some more generic versions for editing or adding purposes, eg you could do the following :
/*
* #param $affectedElements the collection of elements to be changed
* #param $attribute here means the attribute to be added to each of those elements
* #param $attributeValue the value of that attribute
*/
function add($affectedElements, $attribute, $attributeValue){
for(int i=0; i<$affectedElements.length; i++){
($affectedElements[i]).setAttribute($attribute, $attributeValue);
}
}
If you use a global function to do the work for you, not only your coce is gonna be easier to maintain but also you'll avoid fetching for elements in the DOM many many times, which will considerably make your script run faster. For example, in your previous code you fetch the DOM for a set of specific elements before you can add a value to them, in other words everytime your function is executed you'll have to go through the whole DOM to retrieve your elements, while if you just fetch your elements once then store in a var and just pass them to a function that's focusing on adding or changing only, you're clearly avoiding some repetitive tasks to be done.
Concerning the last function i think code is still incomplete, but i would suggest you use the built in methods for manipulating HTMLOption stuff, if i remember well, using plain JavaScript you'll find yourself typing this :
var category = document.getElem.... . options[put-index-here];
//JavaScript also lets you create <option> elements with the Option() constructor
Anyway, my point is that you would better use JavaScript's available methods to do the work instead of relying on innerHTML fpr anything you may need, i know innerHTML is the simplest and fastest way to get your work done, but if i can say it's like if you built a whole HTML page using and tags only instead of using various semantic tags that would help make everything clearer.
As a last point for future use, if you're interested by jQuery, this will give you a different way to manipulate your DOM through CSS selectors in a much more advanced way than plain JavaScript can do.
you can check out this link too :
replacement for innerHTML
I assume that your question is only about the title changing, and not about the rest; also, I assume you mean changing all elements in the document that have "title" as name attribute, and not the document title.
In that case, you could indeed use document.getElementsByName("title").
To handle the name="title" elements, you could do:
titleElems=document.getElementsByName("title");
for(i=0;i<titleElems.length;i++){
titleInner=titleElems[i].innerHTML;
titleElems[i].innerHTML=titleInner.replace(titleInner.match(".mp4"), "");
}
For the name="description" element, use this: (assuming there's only one name="description" element on the page, or you want the first one)
document.getElementsByName("description")[0].value="Subscribe.";
I wasn't really sure about the keywords (I haven't got a YouTube page in front of me right now), so this assumes it's a text field/area just like the description:
document.getElementsByName("keywords")[0].value=prompt("Please enter keywords:","");
Again, based on your question which just sets the .value of the category thingy:
document.getElementsByName("description")[0].value="<option value='27'>Education</option>";
At the last one, though, note that I changed the "27" into '27': you can't put double quotes inside a double-quoted string assuming they're handled just like any other character :)
Did this help a little more? :)
Sry, but your question is not quite clear. What exactly is your HTML title that you are referring to?
If it's an element that you wish to modify, use this :
element.setAttribute('title', 'new-title-here');
If you want to modify the window title (shown in the browser tab), you can do the following :
document.title = "the new title";
You've reading elements from .value property, so you should write back it too:
document.getElementsByName("title").value = new_title
If you are refering to changing text content in an element called title try using innerHTML
var title = document.getElementsByName("title").value;
document.getElementsByName("title").innerHTML = title.replace(title.match(".mp4"), "");
source: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
The <title> element is an invisible one, it is only displayed indirectly - in the window or tab title. This means that you want to change whatever is displayed in the window/tab title and not the HTML code itself. You can do this by changing the document.title property:
function remove_mp4()
{
document.title = document.title.replace(title.match(".mp4"), "");
}

javascript, how to take value from an input by class?

I use this code to get value from an input box:
var suggest_type = document.getElementById('ac-type').value;
Now I need to apply my js code on several other pages. I heard that it's not nice to repeat an ID on one website. So, I'm thinking to change to use class like this:
var suggest_type = document.getElementByClass('ac-type').value;
This doesn't get the value. How can I use class to get value?
You should stick with using ID's - they only have to be unique within a page.
If you must use classes, you need to use getElementsByClassName():
var elems = document.getElementsByClassName('ac-type');
var value = elems[0].value;
However this function is not well supported on older browsers, which is another good reason to stick with IDs.
Its absolutely fine to repeat ids across a website just not on a single html document.
ID's should be unique within one html page.
It's actually :
var suggest_type = document.getElementsByClassName('ac-type')[0].value;
But I agree with Jon Taylor, ID's can be the same within a website, as long they are not duplicated on the same page.
try using this:
var elements = document.getElementsByClassName('ac-type'); // this is an array containing all matched elements
Use jquery just by using -
$('.ac-type').val();
you will get value.

Categories