Reading localStorage data? - javascript

I'm messing around with some JavaScript and I'm trying to figure out a way to read the localStorage in a way so I can have achievements go off every 10 clicks or what ever. Here's the code:
<!DOCTYPE>
<HTML>
<HEAD>
<link rel="stylesheet" type="css/text" href="css.css">
<script>
function clickCounter() {
if(typeof(Storage)!=="undefined")
{
var ten=10;
var value = clickCount;
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " +
localStorage.clickcount + " times.";
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web
storage...";
}
}
function clickCounterReset() {
localStorage.clear();
localStorage.clickcount=0;
document.getElementById("result").innerHTML="You haven't clicked the button once!";
}
function Ach1() {
if (localStorage.clickcount=10) {
localStorage.setitem("GetData" , value);
alert(localStorage.getitem("GetData"));
document.getElementById("Ach1").innerHTML="Successfully reached 100!";
}
}
</script>
</HEAD>
<BODY class="body">
<br>
<br>
<div id="Ach1"></div>
<br>
<br>
<center>
<div class="noLight">
<div class="pointlessbutton" style="cursor: pointer;" onClick="clickCounter()">
<font color="white" size="4">+1</font>
</div>
<br>
<div class="pointlessbutton" style="cursor: pointer;" onClick="clickCounterReset()">
<font color="white" size="4">Reset</font>
</div>
</div>
<div id="result"></div>
</center>
</BODY>
</HTML>
As you may see, the actual script for the clicks works fine, so does all the HTML. However, at the bottom where it says "function Ach1()" is where I'm trying to get the script to read the data and compare it to a value I'd put in, such as 10 to then get it to spit out some HTML covered in pretty CSS and display the achievement.

I took out a BUNCH of your code and tried to clean it up.
Also, I want to point out that I butchered the crap of HTML5, as I see you are just learning. There are some BAD practices in this code, but for what you are trying to accomplish I think/hope you can gleam the import bits out with adopting this as dogma (I got lazy!).
Some things to be aware of:
JavaScript is CaSeSeNsItIvE. So if you start calling variables "clickcounter" and then try to reference as "clickCounter" you'll run into a bunch of errors.
The code I provided below: I mixed CSS in the HTML, and HTML (poor choice of tags) in the JavaScript. I see you had a CSS file, well - yeah, you didn't post it so I didn't have access to it. So I just took it out and added colors throughout.
Remember the power of console.log("your messages goes here");. It's a poor mans debugger/manhole into what your code is doing at any one time. Use it while you learn so you can see what the expected values are (FYI: most browsers have "developer tools" -- if you are using Chrome, then hit F12 -- this way you can SEE the CONSOLE messages (and the ERRORS in your JavaScript as you run it).
Don't be afraid to use functions heavily. It's a great way to organize your code and force yourself to pick up good practices.
Here is the code:
<HTML>
<HEAD>
<script>
function clickCounter() {
if(typeof(Storage)!=="undefined"){
if (localStorage.clickCount){
localStorage.clickCount=Number(localStorage.clickCount)+1;
updateResults();
console.log("Added +1 to Click Count! New value: " + localStorage.clickCount);
goldStarNotification();
}
else{
clickCounterReset(); // Set the click-counter to 0
updateResults();
}
}
}
function updateResults(){
var myCounter = localStorage.clickCount;
document.getElementById("result").innerHTML = "You have clicked the button " + myCounter + " time(s).";
}
function clickCounterReset(){
console.log("The reset was hit!");
localStorage.clickCount=0;
updateResults();
}
function goldStarNotification(){
if (localStorage.clickCount == 10){
console.log("You WIN!!! ZOMG!");
document.getElementById("starNotification").innerHTML = "<center><h1>Successfully reached Level 10!</h1></center>";
}
}
</script>
</HEAD>
<BODY class="body" bgcolor="black", onLoad="clickCounterReset()">
<br>
<br>
<div id="starNotification" style="color: white;"></div>
<br>
<br>
<center>
<div class="noLight">
<div class="pointlessbutton" style="cursor: pointer;" onClick="clickCounter()">
<font color="white" size="4">+1</font>
</div>
<br>
<div class="pointlessbutton" style="cursor: pointer;" onClick="clickCounterReset()">
<font color="white" size="4">Reset</font>
</div>
</div>
<div id="result" style="color: white;">Hey! Update me! :-)</div>
</center>
</BODY>
</HTML>

Related

Block all inappropriate words in the textbox when click button

Below is my code which show me notice of inserting kill , fight, slap when i insert in the textbox.
But i want to block all inappropriate words possible in the textbox like f**k and so on. DO you guys have any ideas. Thanks
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="wrapper" style="width:600px; margin:0 auto;">
<h2></h2>
<input id="txtWords" style="width:300px;" />
<br />
<input type="button" id="btnCheck" onclick="fnCheckForRestrictedWords();" value="Check For
Restricted Words">
</div>
<script type="text/javascript">
function fnCheckForRestrictedWords() {
var restrictedWords = new Array("kill", "fight", "slap");
var txtInput = document.getElementById("txtWords").value;
var error = 0;
for (var i = 0; i < restrictedWords.length; i++) {
var val = restrictedWords[i];
if ((txtInput.toLowerCase()).indexOf(val.toString()) > -1) {
error = error + 1;
}
}
if (error > 0) {
alert('You have entered some restricted words.')
}
else {
// Your logic here
}
}
</script>
</body>
</html>
You need to define all "bad" words and put them in your blacklist. You can use some existing lists as a starting point for your list:
https://github.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/blob/master/en
https://github.com/dariusk/wordfilter/blob/master/lib/badwords.json
http://www.bannedwordlist.com/lists/swearWords.txt
http://www.frontgatemedia.com/new/wp-content/uploads/2014/03/Terms-to-Block.csv
Source: Reddit
If you want to include obfuscated "bad" words you may need to add the to the list as well.
The
includes()
method should work: txtInput.includes(restrictedWords[i]) which returns either true or false. You also want to include more bad words and different ways to write them

What is the correct way to toggle this innerHTML with a conditional statement?

Basically when the div shows or hides, I want to respectively toggle the innnerHTML with a "+" (when hidden) and a "-" (when shown). It works initially, but not subsequently.
$('#summary-head').click(function(evt) {
evt.preventDefault();
$('#summary-bod').slideToggle(1000);
$(this).toggleClass('close');
if(document.getElementById('summary-head').innerHTML = "- Professional Summary") {
document.getElementById('summary-head').innerHTML = "+ Professional Summary";
} else {
document.getElementById('summary-head').innerHTML = "- Professional Summary";
};
});
What would the correct way to do this be? This isn't working.
why don't you just use CSS:
$(document).ready(function(){
$('.wrapper').click(function(){
$(this).toggleClass('switch');
});
});
.wrapper .content2{
display:none;
}
.wrapper.switch .content2{
display:block;
}
.wrapper.switch .content1{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<div class="content1">- Professional Summary</div>
<div class="content2">+ Professional Summary</div>
</div>
The jquery just adds or removes a css class and the css rules do the rest
The simplest way to do this would be to put the +/- icon within it's own span in the element. Then you can provide a function to text() which updates the new setting based on the current. Something like this:
$('#summary-head').click(function(e) {
e.preventDefault();
$('#summary-bod').slideToggle(1000);
$(this).toggleClass('close').find('span').text(function(i, t) {
return t.trim() == '+' ? '-' : '+';
});
});
#summary-bod { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="summary-head">
<span>+</span>
Professional Summary
</div>
<div id="summary-bod">
Foo bar
</div>
Note that when using jQuery it's best to stick with the methods it exposes instead of mixing and matching with native methods. In this case they were redundant anyway as you already have a reference to the clicked element through the this keyword.
You have a bug in your code. Comparison statements should use "==", not "=". It's a really common mistake to try to use "=" for comparisons--don't!
Try the following:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id = "summary-div">
<span id ="summary-head">+ Professional Summary</span><br/>
<div id = "summary-bod">
This is a summary body
</div>
</div>
<script>
$('#summary-head').click(function(evt)
{
evt.preventDefault();
$('#summary-bod').slideToggle(1000);
$(this).toggleClass('close');
if (document.getElementById('summary-head').innerHTML == "- Professional Summary")
{
document.getElementById('summary-head').innerHTML = "+ Professional Summary";
}
else
{
document.getElementById('summary-head').innerHTML = "- Professional Summary";
};
});
</script>
</body>
</html>
Also just a style note--and this is personal preference--IMHO the code would be cleaner if you used a boolean flag to indicate whether or not to display the "+ text" or the "- text"; set/clear that flag in your IF statement and make your decisions based on the flag, not the inner html of a span/label/UI element. Another programmer might come along later and change the text of your UI element (e.g. "Executive Professional Summary" instead of "+ Professional Summary") without realizing you've got code elsewhere that depends on the text. Changing text in the UI shouldn't break code. Just my two cents' worth.
You're assigning a value to innerHTMl in if statement. Try this code:
$('#summary-head').click(function(evt) {
evt.preventDefault();
$('#summary-bod').slideToggle(1000);
$(this).toggleClass('close');
if(document.getElementById('summary-head').innerHTML === "- Professional Summary"){
document.getElementById('summary-head').innerHTML = "+ Professional Summary";
} else {
document.getElementById('summary-head').innerHTML = "- Professional Summary";
};
});
A small twist on Liam's answer using just css. The ~ says to look for a following sibling (in)directly.
.hide { display: none; }
.contentState:checked ~ .collapse {
display: inline-block;
}
.contentState:not(:checked) ~ .expand {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<div class="content">
<input type="checkbox" id="professionalSummaryState" class="contentState hide" style="display:none;">
<span class="collapse hide">-</span>
<span class="expand hide">+</span>
<label for="professionalSummaryState">Professional Summary</label>
</div>
</div>

jquery first click is not working, further clicks works

Here is my code jquery code... first time click not working, further clicks works and also in iphone safari nothing happening. Do we need to add anything specific to safari browser. Any help will be appreciated.
CSS
p.expand-one {
cursor: pointer;
}
p.content-one {
display:none;
}
p.expand-2 {
cursor: pointer;
}
p.content-2 {
display:none;
}
HTML
<div class="sitesection">
<p class="expand-one" onclick="dostuff('.expand-one','.content-one');" > + Click Here To Display The Content </p>
<p class="content-one"> This is the content that was hidden before, but now is... Well, visible!"</p>
<p class="content-one"> This is the content that was hidden before, but now is... "</p>
<p class="expand-2" onclick="dostuff('.expand-2','.content-2');"> + Click Here To Display The Content </p>
<p class="content-2"> This is the content that was hidden before, but now is... Well, visible!"</p>
<p class="content-2"> This is the content that was hidden before, but now is... "</p>
</div>
SCRIPT
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script>
function dostuff(classname1, classname2) {
$(classname1).unbind().click( function(){
$(classname2).slideToggle('fast');
$(classname1).text(($(classname1).text() == '- Click Here To Display The Content') ? '+ Click Here To Display The Content':'- Click Here To Display The Content')
});
}
</script>
Thanks..
It's because you only add the click() event handler after the first call to your doStuff() function. Remove the click() call.
function dostuff(classname1, classname2) {
$(classname2).slideToggle('fast');
$(classname1).text(($(classname1).text() == '- Click Here To Display The Content') ? '+ Click Here To Display The Content':'- Click Here To Display The Content')
}
Or better yet, remove the ugly and outdated on* event attributes and attach your events using unobtrusive Javascript. As you're already using jQuery, here's how you do that:
<div class="sitesection">
<p class="expand"> + Click Here To Display The Content </p>
<p class="content"> This is the content that was hidden before, but now is... Well, visible!"</p>
<p class="content"> This is the content that was hidden before, but now is... "</p>
<p class="expand"> + Click Here To Display The Content </p>
<p class="content"> This is the content that was hidden before, but now is... Well, visible!"</p>
<p class="content"> This is the content that was hidden before, but now is... "</p>
</div>
$(function() {
$('.expand').click(function() {
$(this).nextUntil('.expand').slideToggle('fast');
$(this).text(function(i, text) {
return text.trim().charAt(0) == '-' ? '+ Click Here To Display The Content' : '- Click Here To Display The Content';
});
});
});
Working example

(IE6) insert content into iframe at current cursor position

I'm currently upgrading a WYSIWYG Rich Text Editor that was based on the DHTML Editor Control (DEC) to use the more modern editor controls in modern browsers. I'm using an iFrame with design mode turned on and a mixture of regular javascript and jquery.
One of my requirements is to insert html content (forms etc) into the iframe so that users can edit them. I have it working in FF + Chrome, but IE is proving a pain. My current code inserts the content at the start of the parent document and not the iframes, I'm using the selection.createRange() function that when used with DEC would insert the content either at the cursor if the control was selected or at the end of the document inside the editor if not.
Currently it only works when I select some text in IE. Heres my current code (apologies if it looks unformatted the firewall at work is blocking a lot of the css + js from stackoverflow), any ideas?
<html>
<head>
<title>Text Editor Test</title>
<style type="text/css">
.toolbar {background-color:#BFC193;width:500px;padding:5px;}
#insertForm {position: absolute;height:60px;width:200px;top:50px;left:50px;border:1pt solid black;background-color:#fff;padding:10px;}
</style>
</head>
<body>
<h1>MSHTML Text Editor</h1>
<form id="frmEdit">
<div class="toolbar" id="toolbar">
<input type="button" name="insertHTML" value="insert html" onClick="showForm();"/>
</div>
<div id="insertForm" style="display:none;">
Insert Content Form
<input type="button" value="OK" style="width: 80px" onClick="insertContent();">
</div>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
// functions to execute once the DOM has loaded.
$(document).ready(function() {
pageInit();
});
function pageInit() {
// create iframe
$('.toolbar').after("<iframe id='frameEdit' style='width:500px; height:400px' ></iframe>");
//insert delay for firefox + webkit browsers before turning on designMode open + close seems to do the job
document.getElementById('frameEdit').contentWindow.document.open();
document.getElementById('frameEdit').contentWindow.document.close();
document.getElementById('frameEdit').contentWindow.document.designMode='On';
}
function showForm() {
$('#insertForm').toggle();
}
function insertContent() {
// turn off form
showForm();
// set test content
var htmlContent = "<p>Insert Test</p>";
var doc = document.getElementById('frameEdit').contentWindow.document;
if (doc.selection && doc.selection.createRange) { // IE
var range = doc.selection.createRange();
range.pasteHTML(htmlContent);
} else { // FF
doc.execCommand('insertHTML', false, htmlContent);
}
}
</script>
</form>
</body>
</html>
Make your button unselectable to stop it nicking the focus from the iframe. You can do this in IE using uneselectable="on":
<input type="button" value="OK" unselectable="on"
style="width: 80px" onclick="insertContent();">

Not knowing how to position the output of Javascript in an HTML page

I am a javascript beginner . I am working on a wordsmith game that display's a clue (on the roll of a dice ) to a word . now i need to display the blank spaces of the word and a clue below it . I am not knowing hot to display the content to the place i want in the page ???
<html>
<head>
<script type="text/javascript">
form1= document.forms[0];
function display()
{
words=new Array("Elephant","Tiger","Panther","Giraffe","Zebra","Anaconda");
phrases=new Array("Largest Land Mammal","Striped Animal moving towards Extinction","Found in the Amazon Jungle","Found in Africa","It helps us Cross","Very Dangerous Reptile");
count = words[i].length;
while(count>0)
{
document.write("__")//to display the word with blank spaces
document.write(""); // space in between characters
count--;
}
}
function show_dice()
{
randomnumber=Math.floor(Math.random()*6);
i=randomnumber;
randomnumber = randomnumber + 1;
document.getElementById("myButton1").value=randomnumber;
document.getElementById("myButton1").disabled="disabled";
}
</script>
<link rel="stylesheet" type="text/css" href="keyboard.css">
</head>
<body>
<form>
<input type="button" id = "myButton1" name ="Button1" onclick="show_dice()" value="Click the Dice!!!">
<h1>Enter Your Guess For the Word Below</h1>
<h2> Clue to the Word is :</h2>
<input type="text" value="" class="keyboardInput">
</form>
</body>
</html>
Just for start, you could to create a <input type=text id=clue /> and to edit it's content by running
document.getElementById("clue").value= "___";
Later, you can to create a <div> and alter it's content through .innerHTML property;
Instead of answering your question I'll recommend reading W3C DOM -Introduction on quirksmode.org. It explains the "why" of Rubens' answer and gives you knowledge to solve similar problems in the future.

Categories