I have to alter the following code somehow to add line breaks to the labels on the buttons generated by AddRemoteButtonText. Tried everything I found on this site, but nothing worked yet (most probably because I`m just starting out coding javascript). Mostly tried adding another variable to the function and then implementing it by "\n" .
var size = 20;
var repeat_timer;
function AddRemoteButtonText(num, posx, posy, wx, wy, color, label, remote, command, initial_delay, repeat_delay)
{
document.write('<div id="' + num + '" class="button ' + color + '" style="position:absolute; top:' + posy + 'px; left:' + posx + 'px; height:' + wy + 'px; width:' + wx + 'px; line-height: ' + wy + 'px;" align="center">' + label + '</div>');
document.getElementById(num).onmouseup = function () { SendIRCommand (num,remote,command,initial_delay,repeat_delay); EndSendCommand (num) };
document.getElementById(num).onmouseleave = function () { EndSendCommand (num) };
}
}
};
Thanks for your answer!
Add '<br>' like in the below example
document.write(variable +'<br/>'+ variable2);
I would probably do it like this (simplified for example purposes):
var i = 0;
var aboveLineBreak;
var belowLineBreak;
function AddRemoteButtonText() {
console.log(i);
//define some text to print to the button
aboveLineBreak = "above br" + i;
belowLineBreak = "below br" + i;
//create a button object
var btn = document.createElement("DIV");
//add our text, including the line break, to the button
btn.appendChild(document.createTextNode(aboveLineBreak));
btn.appendChild(document.createElement("BR"));
btn.appendChild(document.createTextNode(belowLineBreak));
//define our button's CSS style
btn.setAttribute("class", "button red");
//to set the position, do:
//btn.style.position = "absolute";
//btn.style.top = whatever;
//and so on...
//add listeners if needed...
btn.onmouseup = function () { console.log("foo"); };
//finally add the button to the document's body and increment i
document.body.appendChild(btn);
i++;
}
.button {
width: 33%;
height: 45px;
}
.red {
background-color: darkred;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button onClick="AddRemoteButtonText();"> Add Remote Button Text </button>
</body>
</html>
Not the most beautiful buttons, but if you simply substitute my CSS with your own you should have a working line break. If not, we will need you to post your CSS so we can have a look at it.
Related
Style objectPosition Property gives this example of setting objectPosition:
document.getElementById("myImg").style.objectPosition = "0 10%";
However, when I try to set objectPosition it causes my JavaScript to crash.
In the following code I use CSS to set objectPosition like this:
#img1 {
object-position: 0 0;
width: 635px ;
height: 580px ;
}
Near the bottom of function getImg, my debug code (the “insert” statement) shows it set to “0px 0px”. However, if I proceed this with
imgStyle.objectPosition = "0 0";
The “insert” statement and all following statements are not executed. Here’s my full code with the offending statement commented out:
"use strict";
const numberOfFigures = document.getElementsByTagName('figure').length;
const scale = 3; // scaling up factor
// The function "insert" is used purely for debug purposes
function insert(figNum) {
document.getElementById("para").innerHTML = "OK so far" + figNum;
}
// Create all thumbnails & big images.
for (let i = 0; i < numberOfFigures; i++) {
getImg(i + 1);
}
function getImg(figNum) {
// Create the thumbnails and big images
let startPosn = "0px"; // x-coordinate of object-position for thumbnail
var btnDiv = document.createElement('div');
btnDiv.setAttribute("id", "bigImg" + figNum);
btnDiv.style.backgroundColor = "white";
// Get the figure caption
const figcap = document.getElementById("fig" + figNum).firstElementChild;
btnDiv.innerHTML =
'<button type="button"' +
'class="displayBtn"' +
'onclick="hideBigImg (' +
figNum +
')">Hide large image</button>';
const btnPtr = figcap.appendChild(btnDiv);
/* Append the button to the
figcaption */
var imgDiv = document.createElement('div');
imgDiv.setAttribute("id", "imgDiv" + figNum);
if (figNum === 1) {
/* First image needs height: 100vh or only the top slice is
displayed. Other images may be messed up if this is applied to
them. */
imgDiv.innerHTML = '<' + 'img id="img' + figNum + '" ' +
'class = "sprite-img" ' +
'src="bates-sprite.jpeg" ' +
'style="height: 100vh; ' +
'transform-origin: top left; ' +
'transform: scale(' +
scale + ');">';
} else {
imgDiv.innerHTML = '<' + 'img id="img' + figNum + '" ' +
'class = "sprite-img" ' +
'src="bates-sprite.jpeg" ' +
'style="transform-origin: top left; ' +
'transform: scale(' +
scale + ');">';
}
const imgPtr = btnPtr.appendChild(imgDiv);
/* Append the img to the
button */
/* Make imgDiv high enough to hold the scaled up image & make the
accompanying text visible.
IMPORTANT to do this AFTER creating & appending the. */
// Get the height and width of the image
let img = document.getElementById("img" + figNum);
const imgStyle = getComputedStyle(img);
// Set imgDiv to exactly hold image
imgDiv.style.width = parseInt(imgStyle.width) * scale + "px";
imgDiv.style.height = parseInt(imgStyle.height) * scale + "px";
imgDiv.style.overflow = "hidden"; // Clip off rest of sprite
/*********************** Create thumbnail here *************/
let thumbHTML = '<' + 'div id="thumbDiv' + figNum + '" ' +
'onclick = "showBigImg(' +
figNum + ')" ' +
'style="float: left; ' +
'height: imgStyle.height; ' +
'width: imgStyle.width; ' +
'margin-right: 1.5em; ' +
'background-color: white; ' +
'border: thick solid black;"> ' +
'<' + 'img id="img' + figNum + '" ' +
'class = "sprite-img" ' +
'src="bates-sprite.jpeg" ' +
'style="transform-origin: top left; ' +
'transform: scale(0.5);" ' +
'onclick = "showBigImg(' +
figNum + ')";>' +
'</div>';
figcap.insertAdjacentHTML("afterend", thumbHTML);
/* Append the
thumbnail to the
figcaption */
/* Shrink the div to match the size of the thumbnail, and free up all the
blank space which the full size image would have occupied if it hadn't
been reduced with transform: scale */
let thumbnail = document.getElementById("thumbDiv" + figNum);
thumbnail.style.width = parseInt(imgStyle.width) / 2 + "px";
thumbnail.style.height = parseInt(imgStyle.height) / 2 + "px";
// Set object-position for image in sprite
//imgStyle.objectPosition = "0 0";
insert(imgStyle.objectPosition);
hideBigImg(figNum);
}
function showBigImg(figNum) {
document.getElementById('bigImg' + figNum).style.display = 'block';
document.getElementById('thumbDiv' + figNum).style.display = 'none';
}
function hideBigImg(figNum) {
document.getElementById('bigImg' + figNum).style.display = 'none';
document.getElementById('thumbDiv' + figNum).style.display = 'block';
}
/* Global constants */
:root {
--shrink: 0.30;
/* Size compressed to 30% */
}
figure {
display: block;
width: 96%;
float: left;
border-width: thin;
}
figcaption {
background-color: yellow;
}
.sprite-img {
background-repeat: no-repeat;
object-fit: none;
}
#img1 {
object-position: 0 0;
width: 635px;
height: 580px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="general.css">
</head>
<body>
<figure id="fig1">
<figcaption>Camberley Mail</figcaption>
<p id="para">Text to go with picture.</p>
</figure>
</body>
</html>
The reason why the program 'crashes' or more specifically throws an Exception is because you are trying to modify the properties of a read-only object.
In detail:
const img = document.querySelector("img");
const imgStyle = getComputedStyle(img); // imgStyle is a read-only object
imgStyle.objectPosition = "0 0";
The above code will throw:
Uncaught DOMException: Failed to set the 'object-position' property on 'CSSStyleDeclaration': These styles are computed, and therefore the 'object-position' property is read-only.
As stated in the MDN documentation:
"The object from getComputedStyle is read-only, and should be used to inspect the element's style — including those set by a element or an external stylesheet.
The element.style object should be used to set styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global style attribute."
So, based on the docs, you should use the element.style object for setting the properties:
img.style.objectPosition = "0 0";
I really want long shadows in Javascript but I dont want to code every single one line of them ,so i thought automize it so it works something like this :
for (let i = 0; i < length; i++) {
document.getElementById("text").style.textShadow = i + "px" + ' ' + i + "px" + ' ' + 0 + ' ' + color
}
The problem is it doesn't work. I also tried it with arrays with no luck, the only real working thing is to code every single one of the shadows, but I want an adaptable solution.
How can I try and implement it?
You just need to use an array here to add all shadow variables and then join them as a comma-separated string to get the desired output like:
const color = '#696767';
let shadow = []
for (let i = 0; i < 40; i++) {
shadow.push(i + "px" + ' ' + i + "px" + ' 0 ' + color)
}
document.getElementById("text").style.textShadow = shadow.join(',')
#text {
letter-spacing: 0.5rem;
font-size: 3rem;
margin-top:0
}
<h1 id="text"> HELLO WORLD </h1>
I've been trying to get a smooth scroll animation for a while now, but mainly in JS..
This hasn't been working out that well so I decided to try in CSS3.
Now I want to make this animation responsive by calling a JS function which adds the CSS rules for the animation responsive to the object the animation is for. Here is the JS code I've got so far. I'll also leave a Fiddle, but I'm new to that so things might not work right away.
function getTexts() {
var element = document.getElementsByClassName('toplink');
for (x = 0, len = element.length; x < len; x++){
var ID = element[x].textContent.toLowerCase();
var object = document.getElementById(ID);
console.log(object);
addCSSAnimator(ID);
}
}
function addCSSAnimator(el) {
var sheet = document.styleSheets[0];
var DOM = document.getElementById(el);
var Class = DOM.getAttribute("class");
var Parent = DOM.parentElement.getAttribute("id");
var rect = DOM.getBoundingClientRect();
var rule = ".toplink[ id= '"+el+"' ]:target - #"+Parent+" div."+Class+" {\n" +
"-webkit-transform: translateY( +"+rect.y.toPrecision(4)+'px'+" );\n" +
"transform: translateY( +"+rect.y.toPrecision(4)+'px'+" );\n" +
"}";
console.log("Stylesheet: ",sheet," object: ",DOM," Class: ",Class," offset X&Y:",rect.x," ",rect.y);
console.log(rule);
sheet.insertRule("body { background-color: 0; }", 1);
}
https://jsfiddle.net/dtj46c64/
You may try moving to jquery for this solution. Use document.ready and window.resize functions to handle the animation and also instead of for loop. use the jquery .each() function to get the elements. Try working around the following code i changed for you to go along with. Hope this puts you in the right direction to achieve your goal:
<script>
function getTexts() {
$(".toplink").each(function () {
let ID = $(this)
console.log(ID);
addCSSAnimator(ID);
});
}
function addCSSAnimator(el) {
var sheet = document.styleSheets[0];
var DOM = el;
var Class = DOM.attr("class");
var Parent = DOM.parent().attr("id");
var rect = DOM[0].getBoundingClientRect();
var rule = ".toplink[ id= '" + el + "' ]:target - #" + Parent + " div." + Class + " {\n" +
"-webkit-transform: translateY( +" + rect.top.toPrecision(4) + 'px' + " );\n" +
"transform: translateY( +" + rect.top.toPrecision(4) + 'px' + " );\n" +
"}";
console.log("Stylesheet: ", sheet, " object: ", DOM, " Class: ", Class, " offset X&Y:", rect.left, " ", rect.top);
console.log(rule);
sheet.insertRule("body { background-color: 0; }", 1);
}
$(window).on('resize', function () {
getTexts();
});
$(document).ready(function () {
getTexts();
});
</script>
Notice i changed the rect.y to rect.top as on some browsers the getBoundingClientRect fucntion does not return x and y values but left and top are always filled.
Also dont know why you are getting id of the parent of the object as there is no id set to the parent of the anchor class="toplink" so it will always return as null or empty.
Sorry for not a 100% answer as got busy but i hope the solution so far i suggested will help you tweak and find what your looking for.
I try to add a to an HTML-Document and link it to an image using the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="de">
<head>
<title>Website</title>
<script type="text/javascript">
function addArea(map, xstart, ystart, xende, yende, idCol, col) {
area = document.createElement("area");
area.shape = "rect";
area.coords = "" + xstart + ", " + ystart + ", " + xende + ", " + yende + "";
area.href = "#" + idCol;
area.title = col;
area.alt = col;
/*
area.shape = "\"rect\"";
area.coords = "xstart + \", \" + ystart + \", \" + xende + \", \" + yende";
area.href = "\"#\" + idCol";
area.title = "col";
area.alt = "col";
*/ area.setAttribute(
"onclick",
"alert(\"Color: \" + col); return false;"
);
// append the area to the map
map.appendChild(area);
}
function showMap() {
idCol = "text";
// generate the map
mapCol = document.createElement("map");
mapCol.name = "map_" + idCol;
mapCol.id = "map_" + idCol;
addArea(mapCol, 1, 1, 25, 13, idCol, "00FF00");
addArea(mapCol, 25, 1, 49, 13, idCol, "00FF33");
imgCol = document.createElement("img");
imgCol.src = "https://www.google.de/images/srpr/logo3w.png";
imgCol.width = 275;
imgCol.height = 95;
imgCol.style.border = "1px solid #000";
imgCol.usemap = "#name_und_raute_sind_notwendig_bunt_" + idCol;
imgCol.alt = "Farbe auswählen";
imgColArea = document.createElement("p");
imgColArea.appendChild(imgCol);
testcol = "ffffff";
testlink = document.createElement("a");
testlink.appendChild(document.createTextNode("testlink"));
testlink.setAttribute(
"onclick",
"alert(\"Color: \" + testcol); return false;"
);
document.getElementById("area").appendChild(imgColArea);
document.getElementById("area").appendChild(testlink);
alert("map added with " + mapCol.areas.length + " entries.");
}
</script>
</head>
<body onLoad="showMap()">
<div>
before
<div id="area"></div>
after
</div>
</body>
The image should contain linked areas, that alert a text when clicking on them. Unformtunatly the areas do not show up. Does anyone find my mistake?
First of all, your map identifiers mismatch. Also the property name is useMap, not usemap. Use
imgCol.setAttribute('usemap',"#" + mapCol.name);
or
imgCol.useMap = "#" + mapCol.name;
instead. You also have to add your map to the document:
/* ... */
imgColArea.appendChild(imgCol);
imgColArea.appendChild(mapCol);
/* ... */
JSFiddle demonstration
I'm not sure about this, but I think you should append your MAP-element to the document before assigning children in it. To create new elements differs from creating properties to a non-appended element.
if you are experienced with relations between javascript and doctype declaration , any help would be appreciated. i use wordpress and i am trying to include cursor script into a page. the script works without default wordpress doctype, with it - it does not. any suggestions how to make the cursor script work, please?
HTML doctype declaration for my WordPress:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Code for cursor:
<STYLE type="text/css">
<!--
.kisser {
position:absolute;
top:0;
left:0;
visibility:hidden;
}
-->
</STYLE>
<SCRIPT language="JavaScript1.2" type="text/JavaScript">
<!-- cloak
//Kissing trail
//Visit http://www.rainbow.arch.scriptmania.com for this script
kisserCount = 15 //maximum number of images on screen at one time
curKisser = 0 //the last image DIV to be displayed (used for timer)
kissDelay = 1200 //duration images stay on screen (in milliseconds)
kissSpacer = 30 //distance to move mouse b4 next heart appears
theimage = "cur.png" //the 1st image to be displayed
theimage2 = "small_heart.gif" //the 2nd image to be displayed
//Browser checking and syntax variables
var docLayers = (document.layers) ? true:false;
var docId = (document.getElementById) ? true:false;
var docAll = (document.all) ? true:false;
var docbitK = (docLayers) ? "document.layers['":(docId) ? "document.getElementById('":(docAll) ? "document.all['":"document."
var docbitendK = (docLayers) ? "']":(docId) ? "')":(docAll) ? "']":""
var stylebitK = (docLayers) ? "":".style"
var showbitK = (docLayers) ? "show":"visible"
var hidebitK = (docLayers) ? "hide":"hidden"
var ns6=document.getElementById&&!document.all
//Variables used in script
var posX, posY, lastX, lastY, kisserCount, curKisser, kissDelay, kissSpacer, theimage
lastX = 0
lastY = 0
//Collection of functions to get mouse position and place the images
function doKisser(e) {
posX = getMouseXPos(e)
posY = getMouseYPos(e)
if (posX>(lastX+kissSpacer)||posX<(lastX-kissSpacer)||posY>(lastY+kissSpacer)||posY<(lastY-kissSpacer)) {
showKisser(posX,posY)
lastX = posX
lastY = posY
}
}
// Get the horizontal position of the mouse
function getMouseXPos(e) {
if (document.layers||ns6) {
return parseInt(e.pageX+10)
} else {
return (parseInt(event.clientX+10) + parseInt(document.body.scrollLeft))
}
}
// Get the vartical position of the mouse
function getMouseYPos(e) {
if (document.layers||ns6) {
return parseInt(e.pageY)
} else {
return (parseInt(event.clientY) + parseInt(document.body.scrollTop))
}
}
//Place the image and start timer so that it disappears after a period of time
function showKisser(x,y) {
var processedx=ns6? Math.min(x,window.innerWidth-75) : docAll? Math.min(x,document.body.clientWidth-55) : x
if (curKisser >= kisserCount) {curKisser = 0}
eval(docbitK + "kisser" + curKisser + docbitendK + stylebitK + ".left = " + processedx)
eval(docbitK + "kisser" + curKisser + docbitendK + stylebitK + ".top = " + y)
eval(docbitK + "kisser" + curKisser + docbitendK + stylebitK + ".visibility = '" + showbitK + "'")
if (eval("typeof(kissDelay" + curKisser + ")")=="number") {
eval("clearTimeout(kissDelay" + curKisser + ")")
}
eval("kissDelay" + curKisser + " = setTimeout('hideKisser(" + curKisser + ")',kissDelay)")
curKisser += 1
}
//Make the image disappear
function hideKisser(knum) {
eval(docbitK + "kisser" + knum + docbitendK + stylebitK + ".visibility = '" + hidebitK + "'")
}
function kissbegin(){
//Let the browser know when the mouse moves
if (docLayers) {
document.captureEvents(Event.MOUSEMOVE)
document.onMouseMove = doKisser
} else {
document.onmousemove = doKisser
}
}
window.onload=kissbegin
// decloak -->
</SCRIPT>
<!--Simply copy and paste just before </BODY> section of your page.-->
<SCRIPT language="JavaScript" type="text/JavaScript">
<!-- cloak
// Add all DIV's of hearts
if (document.all||document.getElementById||document.layers){
for (k=0;k<kisserCount;k=k+2) {
document.write('<div id="kisser' + k + '" class="kisser"><img src="' + theimage + '" alt="" border="0"></div>\n')
document.write('<div id="kisser' + (k+1) + '" class="kisser"><img src="' + theimage2 + '" alt="" border="0"></div>\n')
}
}
// decloak -->
</SCRIPT>
The script is riddled with very old browser detection code, this could cause it to break in 'newer' browsers with a stricter DOCTYPE.
Try to remove the 'language="JavaScript1.2"' in the script tag. If that doesn't work you'd have to rewrite the browser detection.
The actual script isn't very complicated though so perhaps you could find parts elsewhere and combine them.
You need to do two things:
Hide the cursor (which is done with CSS)
Fetch the mouse position and place your own cursor there (typically an image). For this you will need a script that fetch the mouse position.
Shouldn't be too hard :)