This is my first post on SO and my first time making a Chrome Extension. I've read alot of documentation, but I am still unsure how to get this to work. Below are my html and js files. I want to be able to type something in the source box and have the have the word print out in the results area in real time. I have tested this code on my local host so i know it works, but for some reason it is acting up as a chrome extension.
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="source"></textarea>
<div id="result">
</div>
</body>
</html>
Here's the js:
function main() {
document.getElementById('source').keydown(function() {
var source = document.getElementById('source').value;
var outputValue = source.replace(/command/gi, "⌘")
.replace(/tab/gi, "⇥")
.replace(/return/gi, "⏎")
.replace(/option/gi, "⌥")
.replace(/control/gi, "⌃")
.replace(/esc/gi, "⎋")
.replace(/left/gi, "←")
.replace(/down/gi, "↓")
.replace(/up/gi, "↑")
.replace(/right/gi, "→")
.replace(/shift/gi, "⇧")
.replace(/eject/gi, "⏏")
.replace(/caps\s\(lock\)/gi, "⇪")
.replace(/save/gi, "⌘ + S")
.replace(/print/gi, "⌘ + P")
.replace(/find/gi, "⌘ + F");
document.getElementById("result").innerHTML = outputValue;
}
}
1) What wOxxOm said in the comment: element.keydown(function() { ... }) does not exist. This definitely comes from some jQuery code - you could use that if you add it to your extension, or you could use addEventListener.
2) You declare a function main(), but nothing ever calls it. A good place to call it would be a DOMContentLoaded event listener on document:
document.addEventListener("DOMContentLoaded", main);
function main() {
/* ... */
}
Related
So... this is weird?! when i try and use an ACE editor in google chrome in the following context:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style>
body {
background-color: rgb(0, 0, 0);
}
.preview {
position: fixed;
margin: 0 auto;
width:800px;
height:600px;
background-color:#3D3D3D;
}
#code {
width:800px;
height:600px;
position: fixed;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="preview" id="preview_layer_1" style="z-index:0;">
nothing much yet
</div>
<div class="preview" id="preview_layer_2" style="z-index:1; background-color:;">
</div>
<div id="code" style="z-index:2;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.3/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$("#code").hide();
$(".preview").dblclick(function(){
$("#code").fadeIn();
})
$("#code").dblclick(function(){
$("#code").fadeOut();
})
});
var Editor = ace.edit("code");
var Haxe = ace.createEditSession("","ace/mode/haxe");
var JSON = ace.createEditSession("","ace/mode/json");
Editor.setTheme("ace/theme/monokai");
Editor.setSession(Haxe);
Editor.focus();
</script>
</body>
so like any sane person i go to chrome dev tools to check whats going on and then suddenly it works!
so i reload it repeat the steps without opening devtools and then wait...
but nothing happens! and i don't know where to start the code looks fine to me but i'm sure its just a dumb error that i've made, right?
Thanks in advance
You need to call Editor.resize() when changing position or display of the editor container element, to allow the editor to adapt to the size changes.
It works when opening chrome devtools, because window size changes, and that calls the resize() method.
The following should work:
$(".preview").dblclick(function(){
$("#code").fadeIn();
Editor.resize();
})
Basically its a div that changes the color after clicking on it.
I would like to make the div save its color after refreshing the page - I don't think cookies are good idea because it will save the color on user pc.
I need to make it the same color for everyone visiting the site.
Here's the code...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>change</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
.color {
width: 400px;
height: 400px;
background: black;
margin: auto auto;
}
.clicked {
background-color: red;
}
</style>
</head>
<body>
<div class="color" id="change" onclick="changeColor();"></div>
<script>
$('.color').click(function(){
$(this).toggleClass('clicked');
});
</script>
</body>
</html>
Where do i start?
Very simple JSON Database Example
I have written some code that will enable you to save the state of the background color in a JSON file, which you would store on your server.
Essentially, the JSON file functions as a simple database (you probably shouldn't implement it this way, but it's simple enough for a beginner to understand) which centralizes the data, allowing all the users to see the box in the same state.
This is how you could achieve this:
index.js:
$.getJSON("https://api.myjson.com/bins/4zzaa", function(data){
if (data.clicked) {
$("#box").addClass("clicked");
}
$("#box").addClass("loaded");
})
.fail(function(){
//Handle JSON fetch error
});
$('#box').click(function(){
var isClicked = $(this).hasClass("clicked") ? false : true;
var str = JSON.stringify({clicked: isClicked});
$.ajax({
url:"https://api.myjson.com/bins/4zzaa",
type:"PUT",
data: str,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data, textStatus, jqXHR){
$("#box").toggleClass("clicked");
}
})
.fail(function(){
//Handle PUT error
});
});
https://api.myjson.com/bins/4zzaa:
{
"clicked": "true"
}
I seriously suggest doing some reading on jquery.getJSON() and jQuery.ajax(). These will be a good starting point for you.
Here's my fiddle - note that you will have to replace the URLs in the getJSON and ajax methods when you use it.
Hope this helps!
Try this:
Before refresh:
var color = "value";
localStorage.setItem("color", color);
After refresh:
var color = localStorage.getItem("color");
You can achieve this either by setting cookies or localstorage.
I have implemented the functionality using localstorage.
Try it in your code it will work
$(function(){
if(localStorage.getItem("divClicked")){
$('.color').addClass('clicked');
}
else{
localStorage.setItem("divClicked",false);
}
});
$('.color').click(function(){
localStorage.setItem("divClicked", !localStorage.getItem("divClicked"));
$(this).toggleClass('clicked');
});
Its better if you use the id instead of .color. Here is a solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>change</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
.color {
width: 400px;
height: 400px;
background: black;
margin: auto auto;
}
.clicked {
width: 400px;
height: 400px;
background-color: red;
margin: auto auto;
}
</style>
</head>
<body>
<div class="color" id="change" onclick="changeColor();"></div>
<script>
function changeColor(){
$('#change').toggleClass('clicked');
$('#change').toggleClass('color');
if(typeof(Storage) !== "undefined") {
localStorage.setItem("color", $('#change').attr('class'));
}
}
$(document).ready(function(){
if(typeof(Storage) !== "undefined" && localStorage.getItem("color") !='') {
$('#change').attr('class','');
$('#change').attr('class', localStorage.getItem("color"));
}
});
</script>
</body>
</html>
You should save data on the server, for example in database or file
So I am having a problem learning how to use AJAX and JSON to retrieve weather information from openweathermap and placing the information into a paragraph in an HTML page.
I found this piece of code here which briefly outlines what I need to do, but I don't want JavaScript alerts, and I can't seem to get it working.
My webpage currently looks like this:
And the code for that is here:
<!DOCTYPE html>
<html>
<script>
function getWeather()
{
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?zip=02878,us",function(result){
var message = ("Weather: "+ result.weather[0].main);
});
});
}
document.write(getWeather().message);
</script>
<head>
<style>
firstDay {
position: absolute;
left: 10px;
top: 100px;
border-radius: 25px;
background: #8AC007;
padding: 20px;
width: 300px;
height: 550px;
}
</style>
</head>
<body>
<firstDay> <center> <u> <h1> Today </center> </u> </h1>
<p> Weather here </p>
</firstDay>
</body>
</html>
It would be awesome if you guys could show me how to get the result from the getWeather() function into the green box under the Today line.
jQuery's append() is your friend: http://api.jquery.com/append/
Instead of document.write(), just do something like:
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?zip=02878,us",function(result){
var message = ("Weather: "+ result.weather[0].main);
$('firstDay h1').append(message);
});
});
The problem is scoping. Move the .write() inside the callback:
var message = ("Weather: "+ result.weather[0].main);
document.write(message);
Once the Ajax callback returns asynchronously. That is when you have the data to write to the DOM.
I'm starting to learn HTML5+CSS+JS. It was all going fine on my Windows desktop, but when I try doing something on my Linux notebook, no javascript seems to work.
This is the mini tutorial I followed: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/JavaScript
and this is my page with the result: http://www.lele.bbt.net.ar/prueba01/
(As you can see, the JS is not doing a thing).
// JavaScript demonstration
var changeBg = function(event) {
console.log("method called");
var me = event.target,
square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(function() {
clearDemo(me)
}, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 120px;
height: 120px;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<!DOCTYPE html>
<html>
<head>
<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
</body>
</html>
(Here it works, but for some reason, not when I do it on my computer).
I don't know if it can be a priviledge problem or something like that (js has read/write priviledges, not execute. But I guess that's how it should be)
Thanks!
I'm pretty sure it's because the script can't find the button.
You load your script before everything else is loaded, which is fine. But you can have problems like this. To avoid this kind of problems you load the JavaScript file after the HTML.
At the moment if you try to print the var "button" you will receive "null".
The Chrome console when you open the page gives you this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
That means that it is trying to read the property of the button, which is null.
Move the script tag to the very end, just before the closing </body> tag:
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
<script type="text/javascript" src="script.js"></script>
</body>
Here's the entire code for my loop.html file. It first pulls the list of urls from a separate XML file that is in the same directory and then loops through them, given specified time. The time element is the amount it will wait until it cycles to the next page. What I want to do is to use DIV to cycle through the URLs, since iframe is not supported in all the browsers and does not display some of the content when I run the html script. The thing I am not sure about is what to do with the "dashboard.url"--when i want to use a div?
I found this piece of code from a different site--that when you replace the frams['theDisplay'] line with, it sets the div to a webpage--but I want to have something like this, using the dashboard.url
$("#siteloader").html('<object data="http://latimes.com" />');
I am sorry if this is a really long question, and if you get frustrated. I am just trying to learn as I go. Thank you!
Example of list.xml format:
<list>
<url>
<link>http:latimes.com</link>
<time>2</time>
</url>
<url>
<link>http:stackoverflow.com</link>
<time>4</time>
</url>
</list>
Entire HTML code:
<!DOCTYPE HTML>
<!--Created by Megan Chiu - 30 June 2013-->
<html>
<!-- CSS -->
<style type="text/css">
displayArea {
margin: 0;
width: 100%;
}
html, body {
height: 100%
width: 100%;
}
div {
height: 100%;
width: 100%
}
object {
width: 100%;
min-height: 100%;
}
</style>
<head>
<meta charset="UTF-8">
<style type="text/css">
body, html { margin: 0; padding: 0; width: 100%; height: 100%;
overflow: hidden; }
iframe { border: none; }
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var Dash = {
nextIndex: 0,
dashboards: [],
loadXML: function() {
$.ajax( {
type: "GET",
url: "list.xml",
dataType: "xml",
success: Dash.renderXML
});
},
renderXML: function(xml) {
$(xml).find("url").each(function() {
var _link = $(this).find('link').text();
var _time = $(this).find('time').text();
Dash.dashboards.push({url:_link, time:_time});
});
Dash.display();
},
display: function()
{
var dashboard = Dash.dashboards[Dash.nextIndex];
frames['theDisplay'].location.href = dashboard.url;
Dash.nextIndex = (Dash.nextIndex + 1) % Dash.dashboards.length;
setTimeout(Dash.display, dashboard.time * 1000);
}
};
window.onload = Dash.loadXML;
</script>
</head>
<body>
</body>
<iframe id="theDisplay" width="100%" height="100%"></iframe>
</html>
<div id="content1"></div>
<script>
document.getElementById("content1").innerHTML='<object type="text/html" data="header.php" ></object>';
alert('Load_Ok');
</script>
You cannot load content from another website just with pure JavaScript. Period.
http://en.wikipedia.org/wiki/Same_origin_policy
So what you can do? You can make a web request from your server and get Http response from remote server and put them into div element.
<div><%=(new WebClient()).DownloadString("http://www.stackoverflow.com")%></div>
But one of biggest problem is that, since you will download all styles and scripts from remote website then your page probably will not look good. Not even human readable. And if you will keep hitting from same IP to those servers you will may blocked by them.
Good luck.