I'm trying to change the syntax in this code - javascript

I'm a beginner in Javascript. I just wonder how I can use style instead of using a new var in this code.
var style =
"position:absolute;" +
"width:" + newObj.radius + "px;" +
"left:" + newObj.xPos + "px;" +
"top:" + newObj.yPos + "px;";
newImg.setAttribute("style", style);
I want the plus signs to be removed from the end of each line. I tried the following code, but it doesn't work.
newImg.style.position = "absolute;";
newImg.style.width= newObj.radius + "px;";
newImg.style.left = newObj.xPos + "px;";
newImg.style.top = newObj.yPos + "px;";

You question is how to set HTML element's CSS attributes using _Object_.style's properties vs. setting a style using string value
Like this:
newImg.style.position = "absolute";
newImg.style.width= newObj.radius + "px";
newImg.style.left = newObj.xPos + "px";
newImg.style.top = newObj.yPos + "px";
All of these can be found in CSS Reference documentation - look for Javascript syntax for each property

Try this
document.getElementById("theIdYouMadeInHTML").style.property = new style;
As shown in here: https://www.w3schools.com/js/js_htmldom_css.asp

Related

Constructed string for style value not working

function tickleTux() {
var tuxImg = document.getElementById('tux');
tuxImg.style.transition = "transform .5s";
tuxImg.addEventListener('click', itTickles, false);
function itTickles() {
var addRotation = 10;
var rotationValue = '"' + 'rotate' + '(' + addRotation + 'deg' + ')' + '"'
tuxImg.style.transform = rotationValue;
console.log(rotationValue);
}
Basically, this adds a rotation style to an img and makes it rotate.
I just want to know why adding the value to the transform property in this way doesn't work. Why?
The console.log command prints out: "rotate(10deg)"
So what's stopping it from functioning? Some kind of rule?
Thanks for your help.
The value shouldn't contain " around it.
var rotationValue = 'rotate(' + addRotation + 'deg)';

Trouble with regex in javascript; any content within <angular> brackets disappear

I am trying to parse a formula, and display it on screen.
For example I should be able to take <path>T Q, where <path>T cannot change, and Q is a variable. It accepts it,however when printing it on screen again the only thing that will appear is T Q. I want <path>T Q to appear fully.
Other examples of accepted formulae are
(B & A)
~A
~(B&A)
<path>T (B & A)
etc
My code is something like this
var beginPartBUC = '^<path>\\(',
beginPart = '^\(',
unaryPart = '(?:~|<path>T)',
propOrBinaryPart = '(?:\\w+|\\(.*\\))',
subwffPart = unaryPart + '*' + propOrBinaryPart,
endPart = '\\)$';
// binary connective regexes
var conjRegEx = new RegExp(beginPart + '(' + subwffPart + ')&(' + subwffPart + ')' + endPart), // (p&q)
implRegEx = new RegExp(beginPart + '(' + subwffPart + ')->(' + subwffPart + ')' + endPart), // (p->q)
equiRegEx = new RegExp(beginPart + '(' + subwffPart + ')<->(' + subwffPart + ')' + endPart); // (p<->q)
// untilRegEx = new RegExp(beginPartBUC + '(' + subwffPart + ')U(' + subwffPart + ')' + endPart); //<path>(p U q))
As Barmar pointed out, you're writing to html and <path> resembles valid html. You can do this
currentFormula.html('<strong>Current formula:</strong><br>' + wff.ascii.replace(/>/g, ">").replace(/</g, "<"))
As an additional note, backticks are used on StackOverflow like this: `sample code` which produces sample code. This feature is available in comments as well.
Alternatively, in posts (not comments), you can indent each line with a tab or four spaces (easily done by pressing { } in the post editor.

Javascript style using getBoundingClientRect not working

Hi I am trying to use getBoundingClientRect javascript function but the problem is this only seems to work for 1 of my elements. Here is the code.
function getDataXML(getID, cellId) {
var divMain = document.getElementById('Main');
var divCell = document.getElementById(cellId);
var divHoverControl = document.getElementById(getID);
var rectMain = divHoverControl.getBoundingClientRect();
var rectCell = divCell.getBoundingClientRect();
var divWidth = divHoverControl.offsetWidth;
var cellWidth = divCell.offsetWidth;
alert(rectMain.left + " " + rectMain.right + " " + divWidth + " " + cellWidth);
}
Its seems as though the page gets the elements using there ID correctly as I get no error and setting some style attributes works for each element but I only seem to get a result for my rectCell and cellWidth variables but the exact same code for rectMain and DivWidth dont seem to work. Any help would be greatly appreciated.

How would I detect CSS Transition support on :before pseudo-elements with javascript?

I'm trying to use CSS Transitions with a :before selector and currently the only browser that supports this is Firefox. I can create a jQuery fallback with no problem, but I'm not sure how to do feature detection with a pseudo-element like that.
Here's a JSBin which shows the HTML and CSS that I'm working with.
(... and here's a similar SO question, but about using regular elements.)
Update: wow, even the platform preview of IE10 has support for this, what's up with that webkit?!
(Edit: solutions moved to answer below)
I know the recommendation states that you should use fallbacks and not polyfills, but just between you and me, using unconditional polyfills isn't all that awful for bleeding edge stuff like CSS3.
If you must know the feature status, you could use Modernizr, but if you're using a library anyway you might as well just use Selectivizr and get full CSS support cross browser.
Aha! Here is a very nice fiddle from the Modernizr folks over at github. Basically it checks if the computed style value for a pseudoelement has changed from its original value within a timespan that is shorter than the transition duration. The problem, of course, is the unreliability of using setTimeouts (syncing problems) and the fact that you need to postpone everything until the setTimeout test is complete. Check your console to see whether the browser has pseudoelement transitions or not.
To be fair, upcoming IE10 does support transitions on generated content (tested myself on Windows 8 Enterprise trial).
Actually, I'm sure there is no need for detection of this type of things. Transitions are just slight improvement, not a critical functionality. So it's perfectly OK to have transitions working in more advanced browsers while not having it in less advanced ones.
But if you need to detect it, considering this cannot be reliably detected directly, you could use browser engine detection by testing existence of standard global JS objects. For example, since we know IE10 has support for transitioning generated content, we can quite future-proofly filter IE9 and older IEs with document.all && !window.atob condition. Opera can be detected by testing existence of window.opera, so when Opera will fix this issue, we could use window.opera && !someGlobalObjectAddedInFixedOpera condition to detect older versions. It's possible that WebKit can be detected some similar way.
Thanks to #Asad for digging up some handy code, I was able to come up with a nice solution here's the jQuery version:
$(function() {
var isTransitionSupported = (function (pseudo, transProp, transPropStart, transPropEnd) {
var id = pseudo + transProp + '-' + (new Date()).valueOf(),
prefixes = ['o', 'ms', 'moz', 'webkit'],
prop = "transition: " + transProp + " 99s linear;",
allprops = (function () {
var props = "";
for (var l = prefixes.length; l--;) {
props += "-" + prefixes[l] + "-" + prop;
}
return props + prop;
}()),
$css = $("<style>" +
"#" + id + "{position:absolute;left:-999em;}" +
"#" + id + ":" + pseudo + "{display:block;content:'M';" + transProp + ":" + transPropStart + ";}" +
"#" + id + ".t:" + pseudo + "{" + allprops + transProp + ":" + transPropEnd + ";}" +
"</style>"),
$bct = $('<div id="' + id + '" />');
$css.appendTo("head");
$bct.appendTo("body");
try {
// get style value before any changes
window.getComputedStyle($bct[0], ':' + pseudo).getPropertyValue(transProp);
$bct.addClass("t");
// test style after changes
return (window.getComputedStyle($bct[0], ':' + pseudo).getPropertyValue(transProp) !== transPropEnd);
} catch (e) {}
return false;
}("before", "width", "0px", "1000px"));
});
Here's a version that doesn't use jQuery:
var isTransitionSupported = (function (pseudo, transProp, transPropStart, transPropEnd) {
var ticks = (new Date()).valueOf(),
id = pseudo + transProp + '-' + ticks,
prefixes = ['o', 'ms', 'moz', 'webkit'],
prop = "transition: " + transProp + " 99s linear;",
allprops = (function () {
var props = "";
for (var l = prefixes.length; l--;) {
props += "-" + prefixes[l] + "-" + prop;
}
return props + prop;
}()),
body = document.body || document.createElement('body'),
node = document.createElement('div'),
css = "<style>" +
"#" + id + "{position:absolute;left:-999em;}" +
"#" + id + ":" + pseudo + "{display:block;content:'M';" + transProp + ":" + transPropStart + ";}" +
"#" + id + ".t" + ticks + ":" + pseudo + "{" + allprops + transProp + ":" + transPropEnd + ";}" +
"</style>",
bct = document.createElement('div'),
isSupported = false;
bct.id = id;
node.innerHTML += css;
node.appendChild(bct);
body.appendChild(node);
try {
// get style value before any changes
window.getComputedStyle(bct, ':' + pseudo).getPropertyValue(transProp);
bct.className += "t" + ticks;
// test style after changes
isSupported = (window.getComputedStyle(bct, ':' + pseudo).getPropertyValue(transProp) !== transPropEnd);
} catch (e) {}
node.parentNode.removeChild(node);
return isSupported;
}("before", "width", "0px", "1000px"));
document.documentElement.className += ' ' + (isTransitionSupported ? '' : 'no-') + "pseudo-trans";
Here's all that code in a gist on github, if anyone wants to fork and improve it.

why wont jQuery remove() work in this case?

Im trying to cause a canvas element to be added to the DOM and then removed after a set time. The killbox() function gets called, but the element is not removed. I believe I have the syntax right, and that there is some underlying issue with removing dynamically added DOM elements.
//con is short for console.log()
function spawnCanvas(e) {
con(e);
var boxheight=50;
var boxwidth=50;
var xpos = e.clientX - boxwidth/2;
var ypos = e.clientY - boxheight/2;
var id = xpos.toString() + ypos.toString();
con("id:" + id);
var tag = "<canvas width='" + boxwidth +
"' height='" + boxheight +
"' style='position:absolute; border:1px solid #000; left:" +
xpos + "px; top:" + ypos + "px;' id='" + id + "'></canvas>";
con(tag);
var t = $(tag);
$("body").append(t);
var p = setTimeout("killbox(" + id + ")", 1500);
}
function killbox(id){
con("in killbox. id:" + id);
$('#id').remove();
}
Within killbox you are removing the element with the literal id id. Instead try;
$('#' + id).remove();
The above will remove the element that has the id that the "id" variable is set to.
Are you sure you don't want $("#" + id).remove();?
because you are searching with an element with the ID id, but you rather wanted to pass the parameter from the function
function killbox(id){
con("in killbox. id:" + id);
$('#'+id).remove();
}

Categories