Javascript function unable to access CSS styling - javascript

Javascript function unable to access CSS styling
I can't figure out why the Javascript function below is unable to access any of the CSS styling! The demo script's
idea is for a small menu of options to appear at mouse coordinates when you Right-click. Code follows...
<style type="text/css">
.MiniMenuText {
Font-family: "Comic Sans MS";
Font-size: 11px;
Font-weight: Normal;
Font-style: Normal;
Text-decoration: None;
Text-align: Left;
Color: #FFFFFF;
Height:0;}
.MiniMenuBox {
-moz-box-shadow: 3px 3px 4px #000;
-webkit-box-shadow: 3px 3px 4px #000;
box-shadow: 3px 3px 4px #000;
Padding: 1px;
Width: 175px;
Height: 80px;
Background-color: #686868;
Border-style: Solid;
Border-color: #A0AAA0;
Border-width: 1px;
Text-align: Center;}
<!--
A:hover {Color:Black; Background-color:#FFFFFF;}
-->
</style>
<script type="text/javascript">
function RunMiniMenu() {
var X=window.event.clientX;
var Y=window.event.clientY;
document.write('<div Class="MiniMenuBox"; Style="Position:Absolute; Left:'+X+'px; Top:'+Y+'px;";>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 1</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 2</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 3</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 4</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 5</a></div>');
}
</script>
<body oncontextmenu="RunMiniMenu(); return false;"; </body>

One error is the ; you put after every HTML attribute. The other one is mentioned by Michael Berkowski (the missing > within the body tag).
One more thing to keep in mind: When you write to the document AFTER the page has fully loaded (i.e. after the document is closed), a write to it will yield a new document that lacks the styles.
EDIT
<style>
/* Your styles here */
</style>
...
<body oncontextmenu="runMiniMenu();">
<!-- Whatever markup you need comes here! -->
<script type="text/javascript">
function runMiniMenu(e) {
var X = e.clientX,
Y = e.clientY;
var div = document.createElement('div');
div.createAttribute('class', 'MiniMenuBox');
div.createAttribute('style', 'position: absolute; left:'+X+'px ...
for ( var i=1; i < 6; i++ ) {
var a = document.createElement('a');
a.createAttribute('target', '_blank');
// You get the point!
...
div.appendChild(a);
}
document.getElementsByTagName("body")[0].appendChild(div);
return false;
}
</script>
</body>

Everyone is correct about the errors in your syntax and about document.write. Abandon document.write and you will be much better off.
If you are simply trying to put that html in the body tag after the page loads then I would use innerHTML
So it would look like this:
<script type="text/javascript">
function RunMiniMenu() {
var X=window.event.clientX;
var Y=window.event.clientY;
var body = document.getElementsByTagName("body");
body.innerHTML = "<div class='MiniMenuBox' style='position:absolute; left:"+X+"px;
top:"+Y+"px;'><a href=''; target='_blank'; class='MiniMenuText'>Option 1</a><br/></div>";
}
</script>
<body onload="RunMiniMenu(); return false;"> </body>

Related

Save contentEditable into html file with javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

How do I display a DIV when an anchor is active in HTML

How do I make the following code only display when the url ends in #404?
<!--404 code-->
<style>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
border-color: #ff0263;
box-sizing: border-box;
}
</style>
<body>
<font face="century gothic">
<div class="div1" name="div1">
<span id='close' style="cursor:pointer" onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span> The vite you were looking for could not be found. <button class="button button5">What do I do now?</button></div>
</font>
<script>
window.onload = function() {
document.getElementById('close').onclick = function() {
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
</script>
<style>
#close {
float: right;
display: inline-block;
padding: 2px 5px;
background: #ccc;
}
#close:hover {
float: right;
display: inline-block;
padding: 2px 5px;
background: #ccc;
color: #fff;
}
</style>
<script>
$(document).ready(function() {
$("#id1").click(function() {
$(".div1").css('display', 'block');
});
});
</script>
I run this website called Vite - vite.website (Google: Vite Flash Engine). and if I could set it up so that when it reaches a 404, it will redirect to vite.website/#404. How do I make the following code visible only when the anchor, #404 is active?
Thanks!
This is css.but you can use jquery.
you can get the hash of the current url of the page and use if statement for your aim.
you can get the hash location of a webpage using
window.location.hash
So, maybe something like this can work (assuming you're using jQuery)
function hashIs404() {
var hash = location.hash.slice(-1);
if (hash === "404") {
//Display things
//$(selector).addClass(classname); recommended
} else {
//Hash is not 404
//$(selector).removeClass(classname); recommended
}
}
and call this function hashIs404(); by binding it to window.onload:
window.onload = hashIs404;
As for actually displaying it, use the if case and
$("head").append("<link rel='stylesheet' href='stylesheet-location.css');
Hope I could help if not entirely solving the issue :)

Code works in jsfiddle but not in html page [duplicate]

This question already has an answer here:
jquery code works on codepen/jsfiddle but not html page
(1 answer)
Closed 6 years ago.
I am using code from Max lines textarea to create a textarea with only 9 lines and this code works perfectly on my jsfiddle, https://jsfiddle.net/cityFoeS/3j48cpzn/ The textarea will not limit the textarea to 9 lines like I want it to.
my HTML:
<html>
<head>
<style>
body {
background: black;
}
textarea {
overflow: hidden;
resize: none;
font-family: courier;
color: white;
outline: none;
line-height: 20px;
margin: 0;
padding: 0;
border: 0;
left: 45px;
position: absolute;
font-size: 14px;
background-color: black;
border-bottom: 1px solid white;
}
div {
font-family: courier;
color: white;
line-height:20px;
position: absolute;
font-size: 14px;
width: 29px;
border-right: 1px solid white;
border-bottom: 1px solid white;
left: 10px;
}
</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var limit = 9; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");
textarea.onkeyup = function() {
var lines = textarea.value.split("\n");
for (var i = 0; i < lines.length; i++)
{
if (lines[i].length <= spaces) continue;
var j = 0;
var space = spaces;
while (j++ <= spaces)
{
if (lines[i].charAt(j) === " ") space = j;
}
lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
lines[i] = lines[i].substring(0, space);
}
if(lines.length>limit)
{
textarea.style.color = 'red';
setTimeout(function(){
textarea.style.color = '';
},500);
}
textarea.value = lines.slice(0, limit).join("\n");
};
</script>
</head>
<body>
<div>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</div><textarea rows="10" cols="50" id="splitLines" onpaste="return false;"></textarea>
</body>
</html>
The problem is that in JSFiddle, you have the option "Load Type" set to "onload" under the JavaScript options.
In your code, however, the JavaScript runs immediately, before the HTML — this will cause the error (and this is what I get when running it as a standalone HTML page):
Uncaught TypeError: Cannot read property 'getAttribute' of null
There are two solutions:
Moving the <script> tags to the end of the <body> tag. For example:
<body>
<!-- all your visible HTML elements -->
<script>
// all your JS code
</script>
</body>
Encapsulating all the JavaScript in a window.onload function or a $(function() {}) (for use with jQuery). For example:
<script>
window.onload = function() {
// all your JS code
};
</script>

Polymer drag-drop event object property contains parent srcElement

I'm building a simple one page app using Polymer. I have created a custom element that contains the Polymer-drag-drop demo. The action of dragging and creating a div works fine, the event object's relatedTarget property holds a reference to the correct drop div. The problem is the srcElement and target property both hold references to the shadowRoot parent polymer element, in this case "workspace-drop".
EDIT:
Logging event.currentTarget on fire also contains a reference to the parentDiv holding the colored children. <div flex horizontal style="border: 1px dotted silver;">
Code is as follows (pretty much the demo but in a polymer element):
<link rel="import" href="/components/polymer/polymer.html">
<script src="/components/webcomponentsjs/webcomponents.js">
</script>
<link rel="import" href="/components/core-drag-drop/core-drag-drop.html">
<polymer-element name="workspace-drop">
<template>
<style>
html {
font-family: 'Helvetica Neue', 'Roboto', 'Arial', sans-serif;
}
body {
height: 100vh;
margin: 0;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
margin: 16px;
}
.dropped {
position: absolute;
border: 1px solid black;
width: 5px;
height: 5px;
}
</style>
<div flex horizontal style="border: 1px dotted silver;">
<core-drag-drop></core-drag-drop>
<div class="box" style="background-color: lightblue;" draggable="false"></div>
<div class="box" style="background-color: orange;" draggable="false"></div>
<div class="box" style="background-color: lightgreen;" draggable="false"></div>
<div id="hello">Hello World</div>
</div>
<div id="drop" hash="test" class="box" style="border: 3px solid silver; position: relative; width: 300px; height: 300px;" draggable="false"></div>
</template>
<script>
(function(){
addEventListener('drag-start', function(e) {
var dragInfo = e.detail;
// flaw #2: e vs dragInfo.event
console.log(e.detail);
var color = dragInfo.event.target.style.backgroundColor;
dragInfo.avatar.style.cssText = 'border: 3px solid ' + color + '; width: 32px; height: 32px; border-radius: 32px; background-color: whitesmoke';
dragInfo.drag = function() {};
dragInfo.drop = drop;
});
//
function drop(dragInfo) {
var color = dragInfo.avatar.style.borderColor;
var dropTarget = dragInfo.event.relatedTarget;
if (color && dropTarget.id === 'drop') {
var f = dragInfo.framed;
var d = document.createElement('div');
d.className = 'dropped';
d.style.left = f.x - 4 + 'px';
d.style.top = f.y - 4 + 'px';
d.style.backgroundColor = color;
dropTarget.appendChild(d);
dropTarget.style.backgroundColor = color;
}
}
Polymer({
ready: function(){
}
});
})();
</script>
</polymer-element>
Any assistance is appreciated!
Figured it out. It is related to this question.
When loggin an event object, currentTarget is null, but when logging event.currentTarget it logs a value. Why is that?
Logging the event after the drag action has completed returns a reference to the object in its completed state. Logging the specific event.target property on drag-start gave reference to the correct object, on start.

Removing dynamic divs made with JS on click

My code knowledge is very limited, comes from CodeHS and Codecademy so bear with me.
So I am trying to make a list of numbers, that can be deleted on click. So far so good with the number list, but I still can't figure how to remove them when I click the div box.
I know theres JSFiddle, but I think this is best I could do:
http://www.codecademy.com/rfabrega/codebits/xZ61aJ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
color: #000;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
</style>
</head>
<body>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
you have to create a function on click that deletes the target div tag:
so in your code, after creating the div element. insert this:
divTag.onclick = function(){this.parentNode.removeChild(this)};
$(document).ready(function(){
$('p').hide();
$("body").on("click",".divContainer",function(){
$(this).remove();
});
});

Categories

Resources