How can I log information without using alert in userscripts - javascript

i have an userscript which traces all the dynamically created tags in javascript of a webpage. the problem here is presently i am using alert box to dispaly the output. The problem with alert() is that it can be very obtrusive. For every alert, you need to click the OK button to proceed which wastes your time. so i want an alternative method like log files other than alert box. how can i do this.
i am restricted to use console.log

I would use some kind of console element statically placed on your page which can be hidden if necessary. See this jsFiddle.
HTML:
<div id="console">
<div class="header">
Console
<span class="expand" onclick="toggleConsole();">+</span>
</div>
<div class="content" style="display: none;"></div>
</div>
CSS:
#console {
position: fixed;
right: 0px;
bottom: 0px;
width: 300px;
border: solid 1px #dddddd;
}
#console .header {
background-color: #ededed;
border: solid 1px #dddddd;
}
#console .header .expand {
padding-right: 5px;
float: right;
cursor: pointer;
}
#console .content {
overflow: auto;
background-color: #F9F9F0;
width: 100%;
height: 180px;
}
Javascript:
function log(text) {
var consoleContent = document.getElementById('console')
.getElementsByClassName('content')[0];
var line = document.createElement('div');
line.className = 'consoleLine';
line.innerHTML = text;
consoleContent.appendChild(line);
}
function toggleConsole() {
var content = document.getElementById('console')
.getElementsByClassName('content')[0];
if (content.style.display === "none") {
content.style.display = "block";
document.getElementById('console')
.getElementsByClassName('expand')[0].innerHTML = "-";
} else {
content.style.display = "none";
document.getElementById('console')
.getElementsByClassName('expand')[0].innerHTML = "+";
}
}
document.onload = function() {
document.getElementById('console')
.getElementsByClassName('expand')[0].onclick = toggleConsole;
};
Use log("some text"); to output to your console !

Install firefox add-on to your Mozilla(if you are using) and you the follwing code:
console.log("test"+your_variable);
So above code will display all logs in console.If IE press F12 and check console.

If a normal user should be able to see it, using the console is not a very user-friendly way.
Define a space on your webpage (a <div> might be handy) where you want the information to be, and just add the messages to that space using javascript (or jQuery) to modify the DOM:
HTML:
<div id='logmessages'>Log messages:</div>
JavaScript
function log(yourMsg) {
document.getElementByID('logmessages').innerHTML() += yourMsg;
}
It might be friendly to allow the user to show/hide the div with a button or another way.

Create a fixed div either at the top, bottom or corner of your page with set width/height and overflow auto, then insert the log entries in it.

Related

How to change all of a div's style attribute using JavaScript?

I'm working on my own in browser live HTML/CSS code editor. What I'm having trouble with is applying the css styles typed out by the user to my div preview pane.
What I currently have is
<html lang="en">
<head>
<meta charset="utf-8">
<title>Code Editor</title>
<style>
.wrapper{
width: 100%;
}
.textWrapper {
width: 30%;
height: 100%;
float: left;
}
#css{
height: 300px;
width: 100%;
}
#html {
height: 300px;
width: 100%;
}
#preview {
height:600px;
width: 400px;
float:left;
border:2px solid black;
margin: 20px;
}
</style>
</head>
<body>
<div class ="wrapper">
<div class ="textWrapper">
<textarea placeholder="CSS..." id="css"></textarea>
<textarea placeholder="HTML..." id="html"></textarea>
</div>
<div id="preview"></div>
<button onclick="launch()">Launch</button>
<button onclick="toggleCSS()">Toggle</button>
<button onclick="clear()">Clear</button>
<script src="bebk9hScripts.js"></script>
</div>
</body>
</html>
and for my script page
function launch() {
document.getElementById("preview").innerHTML = document.getElementById("html").value;
}
function toggleCSS() {
document.getElementById("preview").style = document.getElementById("css").value;
}
but that is not working. Any suggestions? Also I realize using an iframe would be easier but we aren't supposed to.
A simple and effective way to accomplish what you're trying to do is to set the innerHTML of your preview element. This does not prevent you from utilizing HTML, CSS, or JavaScript in any way, so long as all necessary dependencies have been accounted for prior to your preview element. The simple implementation is:
var preview = document.getElementById("preview");
var html = document.getElementById("html").value;
var css = document.getElementById("css").value;
preview.innerHTML = html;
preview.innerHTML += '<style>' + css + '</style>';
However, as a developer in a very rapid environment, I can honestly say, using an interval to refresh the preview is much appreciated when you're trying to quickly update things. It'll be up to you as to how fast of an interval you'll use to refresh, or you could give your users a setting for update intervals.
Keep in mind though, that using intervals can cause undesired behavior such as animations being cutoff, etc. This is why a lot of code editors online use a refresh or run button in the first place. But I'd like to point out the usefulness of utilizing the keyup event that is available to us.
Coupling the keyup event with a timer, a manual refresh button, and an interval would be my recommendation:
var html = document.getElementById("html");
var css = document.getElementById("css");
// Use the `keyup` event as a primary check for updates.
var keyDelay = 1000;
var keyRecieved = false;
var timeSinceLastKeyRecievedInMilliseconds = 0;
document.addEventListener('keyup', prepareForRefresh);
function prepareForRefresh() {
keyRecieved = true;
timeSinceLastKeyRecievedInMilliseconds = 0;
}
function update() {
var preview = document.getElementById("preview");
preview.innerHTML = html.value;
preview.innerHTML += '<style>' + css.value + '</style>';
}
// Use an interval for checking if we should update.
setInterval(function() {
if (keyRecieved) {
timeSinceLastKeyRecievedInMilliseconds += 100;
if (timeSinceLastKeyRecievedInMilliseconds >= keyDelay) {
timeSinceLastKeyRecievedInMilliseconds = 0;
keyRecieved = false;
update();
}
}
}, 100);
// Use a high interval as a fail-safe for flukes.
var interval = 180000;
setInterval(update, interval);
input[type=text] {
margin: 5px;
background-color: #fffa;
border: 2px solid transparent;
border-bottom: 2px solid #fff;
border-radius: 5px;
}
.update {
width: 20%;
padding: 10px;
margin: 5px;
background-color: #f33a;
cursor: pointer;
user-select: none;
}
.primary-content {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
html, body { overflow-y: auto; }
<link href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2940219/PerpetualJ.css" rel="stylesheet"/>
<div id="primary-content" class="primary-content">
<input id="html" type="text" placeholder="HTML" />
<input id="css" type="text" placeholder="CSS" />
<div class="update" onclick="update();">Refresh</div>
<div id="preview"></div>
<div id="refresh-preview"></div>
</div>
The simple example above utilizes a combination of the keyup event, a timer for detecting how long it's been since the user provided input, and a high interval as a fail-safe. This is close to the method utilized by CodePen, and I heavily recommend it for a web focused editor. Feel free to check out my implementation of this in it's simplest form over on CodePen.
Your Code works!
EDIT: Well, at least kind of. It applies the styles directly only to the preview element, not its children (see comments below this post).
Below ist my old answer:
There is nothing wrong with it, and the issue must be somewhere else.
Possible issues that come to mind are:
The CSS entered by the user is not valid, or is overwritten by another stylesheet
The Javascript function to update the file does not get triggered
The elements referenced in the Javascript are the wrong ones
Here is minimal working example using your code:
function toggleCSS() {
document.getElementById("preview").style = document.getElementById("css").value;
}
document.getElementById("apply_css").onclick = toggleCSS;
<textarea id="css" cols="40" rows="5">
width: 150px;
height: 100px;
border: 1px solid green;
background: rgb(170, 200, 250);
</textarea>
<br>
<button id="apply_css">Apply CSS!</button>
<br>
<div id="preview"></div>

Make popup have smart positioning

I am working on a piece of legacy code for a table. In certain cells, I'm adding a notice icon. When you hover over the icon a <span> is made visible displaying some information. I would like to be able to make this <span> smart about its positioning but can't figure out a good method. I can statically position it but depending on which cell in the table it is in it gets lost against the edge of the page. I have done a JsFiddle here demonstrating the issue. Unfortunately, I am not allowed to use anything but HTML, CSS and vanilla JS.
The title attribute to most tags is pretty smart about its position. I have added a title to one of the cells in the table in the jsFiddle (cell containing "Hello"). Is there any way to make my span exhibit the same smart behaviour?
A pop-up can be added before any element by putting the popup html code inside a 'div' with 'position:absolute; overflow:visible; width:0; height:0'.
When these events: 'onmouseenter', 'onmouseleave' are fired on the element, just toggle the popup css attribute 'display' between 'none' and 'block' of the element.
Example on jsfiddle:
https://jsfiddle.net/johnlowvale/mfLhw266/
HTML and JS:
<div class="popup-holder">
<div class="popup" id="popup-box">Some content</div>
</div>
Some link
<script>
function show_popup() {
var e = $("#popup-box");
e.css("display", "block");
}
function hide_popup() {
var e = $("#popup-box");
e.css("display", "none");
}
</script>
CSS:
.popup-holder {
position: absolute;
overflow: visible;
width: 0;
height: 0;
}
.popup {
background-color: white;
border: 1px solid black;
padding: 10px;
border-radius: 10px;
position: relative;
top: 20px;
width: 300px;
display: none;
}

CSS property update not working with mouse click

i am trying to implement accordion.
My accordion should expand on mouse hover on the "accordian head".
And also mouse click on "accordian head" should show/hide the accordion-body.
I got the show/hide working through CSS on hover.
But when i club mouse click event , the functionality is not working
here is the sample
http://jsfiddle.net/yf4W8/157/
.accordion-body{display:none;}.accordion:hover div{display:block;}
you need to change
myDivElement.style.display = none;
myDivElement.style.display = block;
to
myDivElement.style.display = "none"; //double quotes are missing
myDivElement.style.display = "block"; //double quotes are missing
Demo
I have created a working demo, please check the link below not it is working on mouse click. Replace your JavaScript code with this and remove the css properties.
function expandAccordionBody(){
var myDivElement = document.getElementById("accbody" );
var cStyle=window.getComputedStyle(myDivElement, null);
if(cStyle.display=='block'){
myDivElement.style.display='none';
}else{
myDivElement.style.display='block';
}
}
Demo
I took a liberty to change your code a bit. This code works.
Hope that this is what you meant to do....
Instead of using pure Javascript I used jQuery event click and hover.
here is the link for working code
click here for DEMO
HTML code;
<div class="accordion">
<div class="headA">
Head
</div>
<div id="accbody" class="accordion-body">
Body
</div>
</div>
CSS code;
.accordion {
border: 1px solid #444;
margin-left: 60px;
width: 30%;
}
.accordion:hover div {
display: block;
}
.accordion-body a {
background-color: green;
display: block;
color: white;
padding: 25px;
text-align: center;
}
.headA a {
text-align: center;
display: block;
background-color: yellow;
padding: 25px;
}
jQuery code;
$(document).ready(function() {
// on page load hide accordion body
var accordionBody = $('#accbody');
accordionBody.hide();
// first make on click event happening
// when user clicks on "Head" accordion "Body will show up"
$('.headA').click(function() {
if (accordionBody.is(':hidden')) {
accordionBody.slideDown(400);
} else {
accordionBody.slideUp(400);
}
});
$('.headA').hover(function() {
if (accordionBody.is(':hidden')) {
accordionBody.slideDown(400);
} else {
accordionBody.slideUp(400); // turn this off if you want only to slide down and not back up
}
});
});

Blog / Message - How do I fix that empty message divs will piling on / next to each other and make the close button work?

So I'm making a sort of blog posting system or TODO list, however you want to call it.
I want that the following can happen / is possible:
[Working] The user types something in the textarea
[Working] The user clicks on the button.
[Working] A new div will be created with the text of the textarea.
[Working] The textarea will be empty.
[Not Working] The user has got the choice to delete the post by clicking the 'X' on the right side of each '.post' div.
BUT: If I click on the button when there's nothing in the textarea, there appears an empty div, with only an 'X' close button, no background color either. They appear on the same line as the previous message, so you can get a lot of 'X's next to each other.
AND: Clicking the 'X' close button doesn't do anything. No errors in Firefox console.
If it's not clear enough, run this JSFiddle, click the button and I think you'll understand what I mean:
JSFiddle
HTML:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div id="blog">
<h1>Blog post application</h1>
<div id="post-system">
<textarea id="poster" rows="5" cols="50" placeholder="Update status."></textarea>
<div id="button">Post</div>
<div id="posts">
</div>
</div>
</div>
</body>
</html>
jQuery Script:
<script>
$(document).ready(function () {
$('#button').click(function () {
var text = $('#poster').val();
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
});
$('.close-post').click(function () {
('.close-post').parent().hide();
});
});
</script>
CSS:
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
#blog {
background-color: blue;
margin: 50px;
padding: 50px;
text-align: center;
border-radius: 10px;
color: white;
display: block;
}
#poster {
color: default;
resize: none;
border: 1px solid black;
text-decoration: blink;
font-size: 20px;
display: inline-block;
position: relative;
border-radius: 5px;
border: 2px solid black;
padding-left: 10px;
padding-top: 5px;
}
#button {
background-color: #00FFFF;
color: white;
border: 2px solid white;
border-radius: 5px;
cursor: pointer;
width: 50px;
float: left;
}
.post {
background-color: white;
color: blue;
margin-top: 20px;
width: auto;
display: block;
}
.close-post {
margin-right: 10px;
float: right;
color: red;
cursor: pointer;
}
You appear to have two issues:
1) You don't want a post to be created if the textarea is empty
Simple fix . . . check to see if it is empty, before calling the logic to add the new post (and use jQuery's $.trim() to account for only blank spaces):
$('#button').click(function() {
var text = $.trim($('#poster').val());
if (text !== "") {
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
}
});
2) The 'X' buttons are not closing the posts
This also should be a pretty easy fix . . . the reason that they are not working is because the 'X' buttons don't exist when the page is loaded so $('.close-post').click(function() { is not binding to them on page load. You will need to delegate that event binding, so that it will apply to the 'X' buttons that are dynamically added after the page is loaded.
Now, not knowing what version of jQuery that you are using (I can't access jsFiddle from work), I'll point you to the right place to figure out the correct way to do it: https://api.jquery.com/on/
If it is jQuery 1.7 or higher, you would do it like this:
$("#posts").on("click", ".close-post", function() {
$(this).parent().hide();
});
If your version is earlier than that, then investigate the jQuery .delegate() and .live() methods to determine which is the right one to use for your code..
Try this:
$(document).ready(function() {
$('#button').click(function(event) {
event.preventDefault();
var text= $('#poster').val();
if (text === '') {
alert('Nothing to post!');
return;
}
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
});
$('#posts').on('click', '.close-post', function() {
$(this).closest('.post').fadeOut();
});
});
JSFiddle
The way you are doing this, the user will only ever see what they are posting - if you're trying for a chat type where users talk to each other then you will need to store what is being typed on the server side and refresh the screen using something like ajax
but in response to your question, you need to bind the close click like this:
$( "#posts" ).on( "click", ".close-post", function() {
$(this).parent().hide(); // $(this) is the clicked icon, the way you did it above wouldn't as if it had the dollar, it would close all .close-post parents
});
See the part about delegated events: http://api.jquery.com/on/

Javascript show hide css/html/js problem

Some code when I call a showhide method in html is not working correctly. The method shows then hides some html content on this webpage, however, the html or css is not functioning correctly. For example, when the page is loaded in a browser, the space where the div will be shown is just empty space, when there shouldn't be space at all, but when the div is shown it just fills that space. The I think it could be something to do with the css, however I am not to sure. Here is the CSS id I am using to show and hide.
#showAndHide {
text-align: justify;
height: auto;
width: 700px;
margin: auto;
position: relative;
padding-top: 10px;
padding-bottom: 10px;
padding-left: 20px;
padding-right: 10px;
visibility: hidden;
}
and here is a small sample of the html that this is being applied to.
<div id="showAndHide">
<div id="physicalAdress">
<div class="h4">
<h4> What is your physical address? </h4>
</div>
<p> Property name (if you have one) </p>
<input type="text" name="propertyName" /><br/>
that html is within the showandhide div, then within a user input div which is:
.userinput {
text-align: justify;
height: auto;
width: 700px;
margin: auto;
position: relative;
border-collapse: collapse;
padding-top: 10px;
padding-bottom: 10px;
padding-left: 20px;
padding-right: 10px;
border-right-style: solid;
border-left-style: solid;
}
here is the Javascript method.
function showHideDiv()
{
var divstyle = new String();
divstyle = document.getElementById("showAndHide").style.visibility;
if(document.getElementById("yesPrint").checked == true)
{
document.getElementById("showAndHide").style.visibility = "visible";
}
if(document.getElementById("noPrint").checked == true)
{
document.getElementById("showAndHide").style.visibility = "hidden";
}
}
Basically when I run the page, and show the content the styling is becoming skewed and the positioning of the html that is not with the show and hide content is also becoming skewed.
Any ideas/help would be appreciated.
use display:none instead of visibility: hidden;.
visibility: hidden; reserves space for element
Change visibility:hidden to display:none to prevent the element from taking up space when hidden.
You may need to change your JavaScript slightly, but I can't say for sure as you haven't posted it, but you're going to need something like this:
element.style.display = "block"; //Show the element
function toggle_show(id) {
var el = document.getElementById(id);
if (el && el.style) {
el.style.display = el.style.display == 'none' ? 'block' : 'none';
}
}
http://webdesign.about.com/od/css/f/blfaqhidden.htm
Quoting webdesign:
"visibility: hidden hides the element, but it still takes up space in the layout.
display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code."

Categories

Resources