client Side Form validation? - javascript

Does anybody know how is form validation done on this page:
https://donate.mozilla.org/page/contribute/the-mozilla-story?source=20111200_snippet_v1&WT_mc_id=story1
is this a jquery plugin or some html5 feature. Can I use it?

A quick overview of the code shows that it's a custom validation function. Here's what it looks like if it helps.
document.getElementById("wsniceform").onsubmit = function()
{
// Validate the form inputs (make sure their name isn't 'First Name', etc)
if (formValidates())
{
if (document.getElementById("wscc_pp").checked)
{
document.getElementById("wscc_number").disabled = true;
document.getElementById("wscc_expir_month").disabled = true;
document.getElementById("wscc_expir_year").disabled = true;
}
else
{
document.getElementById("wscc_number").disabled = false;
document.getElementById("wscc_expir_month").disabled = false;
document.getElementById("wscc_expir_year").disabled = false;
}
document.getElementById("wsaddr2").value = document.getElementById("wsaddr2").value.replace(originalPlaceholder.wsaddr2, "");
// If it's not checked, nothing should be in the wsamount_other_value field
if (!document.getElementById("wsamount_other").checked)
document.getElementById("wsamount_other_value").value = "";
// webtrends tracking
dcsMultiTrack(
'DCS.dcssip', 'donate.mozilla.org',
'DCS.dcsuri', '/page/cde/Contribution/Charge',
'WT.ti', 'Link: Join Mozilla English Signup',
'WT.dl', 99,
'WT.z_convert', 'Join Mozilla English Signup',
'WT.si_n', 'Join Mozilla English Signup',
'WT.si_x', '2');
return true;
}
else
{
return false;
}
}
wsTest = {
/*
* Test for empty input. This is the only testing function that auto-trims input.
*/
IsEmpty: function(str)
{
if (str.replace(/\s*/g, "").length == 0)
return true;
return false;
},
/*
* Test for a valid email
*/
ValidEmail: function(str)
{
return (/^([\w\-\+]+)(\.[\w\-\+]+)*#([\w\-]+)(\.[\w\-]+)+$/.test(str));
},
/*
* Runs function when all images and DOM has loaded
*/
DOMOnLoaded: function(func)
{
if ((ws.Browser.isIE && !ws.Browser.isCSS3IE) || (ws.Browser.isCSS3IE && ws.Browser.isLegacyMode))
window.attachEvent("onload", wsOnLoad);
else if (document.addEventListener)
window.addEventListener("load", wsOnLoad, false);
else
window.setTimeout(func, 4000);
}
};
As far as a jquery plugin goes, the one i typically go for is this one ->
jquery tools validator
The popup modal itself is another custom function shown here ->
function wsSimpleDialog(title, text)
{
var bgElement = document.createElement("div");
bgElement.id = "d" + parseInt(Math.random() * 100000);
bgElement.style.position = "fixed";
try
{
bgElement.style.backgroundColor = "rgba(218, 236, 248, 0.8)";
}
catch(e)
{
bgElement.style.backgroundColor = "#daecf9"; // Fall back for IE
bgElement.style.filter = "alpha(opacity=80)";
}
bgElement.style.top = "0px";
bgElement.style.left = "0px";
bgElement.style.bottom = "0px";
bgElement.style.right = "0px";
bgElement.style.zIndex = "20000";
document.body.appendChild(bgElement);
msgElement = document.createElement("span");
msgElement.style.display = "inline-block";
msgElement.style.zIndex = "20001";
msgElement.id = "m" + bgElement.id
msgElement.style.position = "fixed";
msgElement.style.top = "50%";
msgElement.style.left = "50%";
msgElement.style.border = "1px solid #0079aa";
msgElement.style.borderRadius = "4px";
msgElement.style.MozBorderRadius = "4px";
msgElement.style.webkitBorderRadius = "4px";
msgElement.style.backgroundColor = "#0789bb";
msgElement.style.color = "#fff";
msgElement.style.padding = "16px";
msgElement.style.fontSize = "14px";
msgElement.style.lineHeight = "16px";
msgElement.style.visibility = "hidden";
msgElement.innerHTML = "<" + "strong style=\"display: block; text-align: center;\">" + title + "<" + "/strong>" + text + "<" + "a style=\"color: #fff; text-align: center; display: block; margin-top: 16px; font-size: 28px; line-height: 32px; font-family: 'LeagueGothicRegular',Impact,Charcoal,'Arial Narrow Bold',Arial,sans-serif\" href=\"#\" onclick=\"return wsCloseSimpleDialog('" + bgElement.id + "')\">OK<" + "/a>";
document.body.appendChild(msgElement);
msgElement.style.marginTop = (-1 * msgElement.offsetHeight / 2) + "px";
msgElement.style.marginLeft = (-1 * msgElement.offsetWidth / 2) + "px";
msgElement.style.visibility = "visible";
}

Related

How to get postition highlighted text in textarea (coords) angular?

I want to get something like this, in textarea. I cant change textarea to contentaditable div. How do I get the position of the selected text? I need this to show this pop-up from above
You should be able to easily convert this into angular code.
This is the basics of what you need to do, its not thoroughly tested but it bare minimum works.
const textarea = document.getElementById('text')
const result = document.getElementById('selected')
const tooltip = document.getElementById('tooltip')
const cols = document.getElementById('text').cols;
const width = document.getElementById('text').clientWidth;
const height = window.getComputedStyle(textarea).lineHeight;
textarea.onclick = function getSelection() {
const pos = {
top: textarea.offsetTop,
left: textarea.offsetLeft,
};
result.textContent = `${textarea.selectionStart}, ${textarea.selectionEnd}`;
let selection
if (textarea.selectionStart) {
selection = textarea.selectionStart;
} else if (document.selection) {
textarea.focus();
const r = document.selection.createRange();
if (r == null) {
selection = 0;
}
let re = textarea.createTextRange();
let rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
selection = rc.text.length;
} else {
selection = 0
}
const row = Math.floor((selection - 1) / cols);
const col = (selection - (row * cols));
const x = Math.floor((col * (width / cols)));
const y = (parseInt(height) * row);
tooltip.innerHTML = "<b>row: " + row + "<br>columns" + col + "<br>width: " + width + "</b>";
tooltip.style.top = `${pos.top+y}px`;
tooltip.style.left = `${pos.left+x+10}px`;
}
textarea {
height: 80px;
line-height: 12px;
overflow-y: scroll;
display: block;
}
#tooltip {
position: absolute;
background:red;
color: white;
}
<textarea id="text">Lopsum</textarea>
<span id="tooltip"></span>
<span id="selected"></span>
The only way I imagine is create a duplicate of the text area (very similar to this SO, (the Owen Kelvin's response) about highligth words in a text area
As we only need the position, we can split the "texarea" and the "background". Futhermore, using the Yurzui response in this another SO we can control when resize the textarea
We can imagine an .html like
<div class="container">
<div
#backdrop
class="backdrop"
[style.width.px]="textWidth"
[style.height.px]="textHeight"
>
<div
class="highlights"
[innerHTML]="sanitizer.bypassSecurityTrustHtml(highlightedText)"
></div>
</div>
</div>
<textarea
#textarea
spellcheck="false"
(resize)="rect = null;"
(select)="applyHighlights(textarea.value)"
(mousedown)="mouseDown()"
(blur)="rect = null"
[ngModel]="textValue"
(ngModelChange)="textValue = $event; applyHighlights(textarea.value)"
(scroll)="handleScroll(); applyHighlights(textarea.value)"
></textarea>
<div
class="tooltip"
*ngIf="rect"
[style.top.px]="rect.y"
[style.left.px]="rect.x"
></div>
See that the "text" is hidden because we has a div container like
.container {
overflow:hidden;
width:0;
height:0;
}
And we make that the dimensions of "text" are condition by the two variables "textWidth" and "textHeight"
The code is
ngOnInit() {
this.resize();
}
resize() {
const event = {
width: this.$textarea.nativeElement.getBoundingClientRect().width,
height: this.$textarea.nativeElement.getBoundingClientRect().height,
};
this.textWidth = event.width;
this.textHeight = event.height;
}
mouseDown() {
setTimeout(() => {
const start = this.$textarea.nativeElement.selectionStart;
const end = this.$textarea.nativeElement.selectionEnd;
if (start == end) this.rect = null;
});
}
applyHighlights(text: string) {
if (text) {
let start = this.$textarea.nativeElement.selectionStart;
let end = this.$textarea.nativeElement.selectionEnd;
if (start == end) this.highlightedText = text;
else {
const selected = text.substr(start, end - start);
this.toolTipText=this.getTooltipText(selected)
this.highlightedText =
text.substr(0, start) +
"<span id='mark'>" +
selected +
'</span>' +
text.substr(end);
this.resize();
setTimeout(() => {
const recArea = this.$textarea.nativeElement.getBoundingClientRect();
const recText = this.$backdrop.nativeElement.getBoundingClientRect();
const rect = document.getElementById('mark').getBoundingClientRect();
rect.y += window.scrollY;
rect.x+=rect.width/2
this.rect = rect.y - window.scrollY < recArea.y ? null : rect;
});
}
}
}
handleScroll() {
var scrollTop = this.$textarea.nativeElement.scrollTop;
this.$backdrop.nativeElement.scrollTop = scrollTop;
var scrollLeft = this.$textarea.nativeElement.scrollLeft;
this.$backdrop.nativeElement.scrollLeft = scrollLeft;
}
And in the stackblitz I put in a custom form component (the reason is that Owen make this work for me

Unable to update image position in css using javascript

There are some runner(animation-image) in my program which move from position x to y when clicked on start button, i want to add a (reverse)button on completion that when clicked on that the image moves from y to x.
Here is the link of my js-fiddle: https://jsfiddle.net/o6egL4qr/
I have added the reverse button but when clicked on that the image doesn't move at all.
class raceManager {
raceCount = 0;
races = [];
addRace() {
var mainContainer = document.getElementById('mainContainer');
mainContainer.appendChild(document.createElement('br'));
var race = new raceClass(this.raceCount);
this.races.push(race);
this.raceCount++;
}
}
class raceClass {
runners = [];
count;
runnerCount = 0;
raceDiv = document.createElement('div');
raceNum = document.createElement('div');
startRaceButton = document.createElement('input');
addRunnerButton = document.createElement('input');
revRaceButton = document.createElement('input');
tableDiv = document.createElement('div');
tableNum = document.createElement('div');
startInterval;
startTime;
revStartTime;
reverseInterval;
constructor(number) {
// store the race no.
this.count = number;
// delcare the race div id
this.raceNum.id = 'raceNum' + this.count;
// delcare the table div id
this.tableNum.id = 'tableNum' + this.count;
// Add raceDiv to the race
document.getElementById('races').appendChild(this.raceDiv);
// Add tableDiv to the race
document.getElementById('tables').appendChild(this.tableDiv);
this.applyDivProperty();
this.initializeButtons();
}
applyDivProperty() {
// apply properties to the tableNum
this.tableNum.style.display = "inline-block";
// apply properties to the raceDiv
this.raceDiv.id = "Race" + this.count;
document.getElementById(this.raceDiv.id).classList.add("raceDivClass");
this.raceDiv.appendChild(this.raceNum);
document.getElementById(this.raceNum.id).innerHTML = '<p>Race: ' + this.count + '</p>';
// append the add race button
this.raceDiv.appendChild(this.addRunnerButton);
// apply properties to the tableDiv
this.tableDiv.id = "Table" + this.count;
document.getElementById(this.tableDiv.id).classList.add("tableClass");
this.tableDiv.appendChild(this.tableNum);
document.getElementById(this.tableNum.id).innerHTML = '<p>Table: ' + this.count + '</p>';
}
initializeButtons() {
// initialize add runner button
this.addRunnerButton.type = 'Button';
this.addRunnerButton.value = 'Add Runner';
this.addRunnerButton.id = 'AddRunner' + this.count;
this.addRunnerButton.onclick = this.addRunner.bind(this);
// initialize start race buttton
this.startRaceButton.type = 'Button';
this.startRaceButton.value = 'Start Race';
this.startRaceButton.id = "startRaceButton" + this.count;
this.startRaceButton.onclick = this.startRace.bind(this);
// initialize reverse race buttton
this.revRaceButton.type = 'Button';
this.revRaceButton.value = 'Reverse Race';
this.revRaceButton.id = "revRaceButton" + this.count;
this.revRaceButton.onclick = this.revRace.bind(this);
}
addRunner() {
var track = new Runner(this); //Initialize the runner object
this.runners.push(track); //Store the runner object in runners array of Race class
if (this.runnerCount > 0) {
// append the start race button
this.raceDiv.appendChild(this.startRaceButton);
}
this.runnerCount++;
}
startRace() {
this.startTime = Date.now();
this.startInterval = setInterval(() => {
this.runners.forEach(function(element) {
element.animate();
});
document.getElementById(this.startRaceButton.id).disabled = "true";
document.getElementById(this.addRunnerButton.id).disabled = "true";
}, 50);
}
stop() {
clearInterval(this.startInterval);
// append the start race button
this.raceDiv.appendChild(this.revRaceButton);
}
revRace() {
this.revStartTime = Date.now();
this.reverseInterval = setInterval(() => {
this.runners.forEach(function(element) {
element.animateReverse();
});
document.getElementById(this.revRaceButton.id).disabled = "true";
}, 50);
}
stopRev() {
clearInterval(this.reverseInterval);
}
}
class Runner {
count = 0;
parent;
track;
sprite;
timeTaken;
trackWidth;
element;
speed;
table;
printCount = 1;
stepCount = 1;
trackNum;
tbl;
lastStep;
constructor(race) {
// initialize the divs
this.parent = race;
this.track = document.createElement('div');
this.sprite = document.createElement('div');
this.table = document.createElement('table');
// assigns #id to table and track corresponding with parent div.
this.table.id = race.tableNum.id + '_Table_' + this.parent.runnerCount;
this.track.id = race.raceNum.id + '_Track_' + this.parent.runnerCount;
this.createUI();
this.timeTaken = ((Math.random() * 5) + 3);
this.speed = this.trackWidth / (this.timeTaken * 1000);
console.log(this.trackWidth, this.timeTaken);
console.log(this.timeTaken * 100);
}
createUI() {
this.count = this.parent.runnerCount;
this.createTable();
this.createTrack();
this.createSprite();
}
createTable() {
var parentDiv1 = document.getElementById(this.parent.tableNum.id);
parentDiv1.appendChild(this.table);
this.table.setAttribute = "border"
this.table.border = "1";
document.getElementById(this.table.id).classList.add("tableClass");
this.tbl = document.getElementById(this.table.id);
this.addRow("Track " + (this.count + 1), "");
this.addRow("Time", "Distance");
}
addCell(tr, val) {
var td = document.createElement('td');
td.innerHTML = val;
tr.appendChild(td)
}
addRow(val_1, val_2) {
var tr = document.createElement('tr');
this.addCell(tr, val_1);
this.addCell(tr, val_2);
this.tbl.appendChild(tr)
}
createTrack() {
var parentDiv = document.getElementById(this.parent.raceNum.id);
parentDiv.appendChild(this.track);
this.track.appendChild(this.sprite);
document.getElementById(this.track.id).classList.add("trackClass");
this.trackWidth = this.track.getBoundingClientRect().width;
}
createSprite() {
this.sprite.id = this.track.id + "_Runner";
document.getElementById(this.sprite.id).classList.add("spriteClass");
this.element = document.getElementById(this.sprite.id);
}
animate() {
// declare time variables
var timeNow = Date.now();
var timespent = timeNow - this.parent.startTime;
var diff = Math.floor(this.timeTaken * 100);
// step is position of sprite.
var step = timespent * this.speed;
// Print table for all tracks with 10 laps.
if ((Math.round(timespent / 50) * 50) == (Math.round(((diff - 25) * this.printCount) / 50) * 50)) {
this.addRow(this.printCount + ": " + timespent, (Math.floor(step)));
this.printCount++;
}
// check condition to stop
if (step > this.trackWidth - 23) {
document.getElementById(this.parent.raceNum.id).innerHTML += 'Winner: Runner' + (this.count + 1);
this.parent.stop();
}
this.element.style.left = step + 'px';
// ------------sprite animation----------------
// start position for the image slicer
var position = (3 - (Math.floor(step / 6.5) % 4)) * 25;
// we use the ES6 template literal to insert the variable "position"
this.element.style.backgroundPosition = `${position}px 0px`;
}
animateReverse() {
// declare time variables
var timeNow = Date.now();
var timespent = timeNow - this.parent.revStartTime;
var diff = Math.floor(this.timeTaken * 100);
console.log(this.count + " position of step " + this.element.style.left);
while (this.stepCount < 2) {
this.lastStep = parseFloat(this.element.style.left);
this.stepCount++;
}
console.log(this.count + " this is lastStep " + this.lastStep);
// step is position of sprite.
var step = this.lastStep - (this.speed * timespent);
// Print table for all tracks with 10 laps.
if ((Math.round(timespent / 50) * 50) == (Math.round(((diff - 25) * this.printCount) / 50) * 50)) {
this.addRow(this.printCount + ": " + timespent, (Math.floor(step)));
this.printCount++;
}
// check condition to stop
if (step < 25) {
document.getElementById(this.parent.raceNum.id).innerHTML += 'Winner: Runner' + (this.count + 1);
this.parent.stopRev();
}
this.element.style.left = step + 'px';
// ------------sprite animation----------------
// start position for the image slicer
//var position = (3 - (Math.floor(step / 6.5) % 4)) * 25;
//this.element.style.backgroundPosition = position + 'px 0px';
}
}
manager = new raceManager();
#tableContainer {
float: left;
}
#addRaces {
text-align: center;
}
.raceDivClass {
margin: 1% auto;
width: 60%;
text-align: center;
border: 1px solid;
}
.tableClass {
text-align: center;
border: 1px solid;
margin: 5px;
float: left;
}
.trackClass {
background-color: black;
height: 30px;
width: 98%;
margin: 1%;
position: relative;
}
.spriteClass {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGgAAAAeCAYAAADAZ1t9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAASwSURBVGhD7Zq/axRBFMfv9u4MxATUSgsVm3QWigYbexuxUkiaKIqNoIUiwRSJoJLCxpSCaJoEYimo/4AgQVRIZxdBEIREYwzc5X74vndvlrm5mdnZ3dm9oPnAsDubu52Z93373pvNFQsJOXO9NUKHsU4vZPH90+IXPt/FA2kEmqbDTKcX8pza7K5I/vAtEJghge7zeSrwlDYbtYlmfWuILxWC8uBmUNoz/784wY4WaPRq9SGJcY+7Mt7GEOzUkB0pkGHi4Ci1K53TEK8h7tTE+pPywL6b3JXJQqBcQ7arQwR87AE34ElPUsPE1ZapODsErFHnnD7AfVWb9oylFYjVFcKoQuQC5kD55hB3Qxrbf17RYbHT+/fpCXGSOEmEaYcevofwhkRxXM0/VCi8azXr3+q1Xw8+LRxZ4cte4PneoHaQ2iVck0gVThVbyOhSRM9YOoFMyR9eW6KmLkAGYW6Vmjx47AViUfSkPC5V9p7nS23q1Z9zH+b33+KuF9iAOocUa0lcKFjubQJ2h51D5zbmIAVM9gc1mzgAE0kdFlFaq+JkQYQBV+FYOYoDGy9Tw3dgQ7QxnUBQUHxAtJfUhqllDhbWam4f525mJDCgMynufZFa13d6BILHsOeEjS6PUjMNtsRHFXgExI2V0PN6egiEkTzFMdlJgM/3zMd1H2Tzhjlqa53TLhLFbsvep9Cob70uFsuffbxJoHWZcq1A5CCZyDUZ7gtxotKDCsafdRHIZSFe9j9wBl1xoIJSuxhUVpIK5eB0JiILHo29EouDtVmLBF4IKjIbWOQkfzYVruENn+ESXFe+upBJeDMQVfWiyXQ5fFQV57oQLyLJL0VlsAfi06yJyhMuIOci7Efdqy0ENzxxonVFI22IY0NDHN1mykaX+nHAmKbw1qhtLLVaze8U1o6Jv9OmdaEYlI1lsLQGGVGwmMKbKZ8KXHIQxnUJn062CgVSFmQTRjySpr8n2nlb3lxTztl8W6+u3x0YOlylrpij1Vi0Hl3uxNx/U9MWIYSPtwZxclukSG2B4qreOTV+3skzBBgbuafVrJ0sVYbO8eUe4r5FMAgEbEnbSSC2l/p0grgRB1jHDGKqjt019kkwvoid4okS4D7O+Qji4MmxiQMonI2cGP/qYwMbt6LSAXFEzpCbyYaJcxuKBAwWJQ5EwATCTScLBeUhVGKRTIWBCgQsVYavcdcF8UZEnVveYPwXfIwNBMJCdF/GNeEZCFnahMzX1A0dgEi6MJALigP1SyiMCdu9wZH7sZBzkGpM5zcBljAZGdNPX964UAhKt0vlwbN8SQs2p/Xq2lTSfzU4hvK0OUily4b0PV1etI4Z+SbBFYMBrIPjO1QuT1N+GedLbVC1FYM9Hyk31fgScHYYE5JhD1Dz/r+fKPoqEJAMILAa1VRaU+HwaPnZwBR3vWJwJCDCUSonsKERKHJMrwLFAYbSbUwRyujanawMZfBikPXTEzvCgKhXPZmhe+/W2ZCuTWXpxQbgyWGFmhGILLb8p6V/AmnKa+Qd3783cCDz0JaGvgmEX4jyaRu8W6N8NM/dPGlvvvk8T5ye2r7mIIQ5PEl5/pyXc4FzIeOLZOMWCn8Bh1eBvOSZzIIAAAAASUVORK5CYII=');
position: absolute;
height: 30px;
width: 25px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="mainContainer">
<div id="addRaces">
<input type="Button" value="Add Race" onclick="manager.addRace()">
</div>
<div id="races">
</div>
<br>
</div>
<div id="tableContainer">
<div id="tables"></div>
</div>
</body>
</html>
I expect it to move from y to x after clicking the reverse button, but it is not moving.
When you run the reverse function the elements are no longer referencing the dom elements.
I am actually not sure why that is, maybe someone else can chime in.
Anyway, this will fix your problem:
Replace this.element.style.left = step + 'px';
With: document.getElementById(this.element.id).style.left = step + 'px';

Javascript - Run once per session

I would like the code below to execute only once when the website first loads.
I tried it with cookies and sessionstorage. But I have never found the right solution. Maybe it was wrong. Does anyone have an idea how I can solve that with session storage? I've never done anything with it. maybe something like this? :
if (!sessionStorage.alreadyClicked) {
$('#my_div');
sessionStorage.alreadyClicked = 1;
}
Any help will be appreciated. Thank You.
var my_div;
topIgnore = 100; // (in pixel units) used for function ignoreTop
window.onload = function() {
my_div = document.getElementById('my_div');
var my_div_style = window.getComputedStyle(my_div);
var width_div = parseInt(my_div_style.width, 10); // remove 'px' from string
var height_div = parseInt(my_div_style.height, 10);
// make sure the property exists, else you can get a NaN
my_div.style.left = 0;
my_div.style.top = 0;
// event
window.onmousemove = function(e) {
// my_div.innerHTML = e.pageX +' - '+ (leftBorder + width_div) +' - '+ width_div;
cursorIsInsideDiv(e);
}
// TO DO: feel free to make similar functions for left/right/bottom
// removes the first 100px
function ignoreTop(top) {
if(top < topIgnore) {
return topIgnore;
}
return top;
}
function cursorIsInsideDiv(e) {
var leftBorder = parseInt(my_div.style.left, 10); // remove 'px' from string
var topBorder = parseInt(my_div.style.top, 10);
// move left
if( e.pageX < leftBorder ) {
my_div.style.left = e.pageX + 'px';
}
// move right
else if( e.pageX > (leftBorder + width_div)) {
my_div.style.left = (e.pageX - width_div ) + 'px';
}
// move up
if( e.pageY < topBorder ) {
var top = e.pageY ;
top = ignoreTop(top);
my_div.style.top = top + 'px';
}
// move down
else if( e.pageY > (topBorder + height_div)) {
my_div.style.top = (e.pageY - height_div ) + 'px';
}
}
}
#my_div {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#my_div {
width: 300px;
height: 150px;
background: #ff0000;
position: absolute;
}
<div id="my_div">
<h2>Newsletter</h2>
Name: <input type="text" name="fullname"><br>
Email: <input type="text" name="email"><br>
</div>
Use JS to set a cookie:
document.cookie = "alreadyClicked=1; expires=Fri, 13 Jan 2017 20:00:00 UTC";
Then, you can check if it exists by defining a function to find the value (from http://www.w3schools.com/js/js_cookies.asp):
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if (getCookie("alreadyClicked") == "1") {
// do stuff if already clicked
} else {
// prompt for click?
}
I just inserted the code between. It worked. Corrected if that is wrong.
if (!sessionStorage.alreadyClicked) {
$('#my_div');
sessionStorage.alreadyClicked = 1;
}

eventlistener javascript problems

I'm trying to learn Javascript and at the moment and I am working on AddEventListener.
What I'm trying to do is to add a new row and so far it works.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.colorOrange {
background-color: orange;
}
.colorBlue {
background-color: blue;
}
.colorYellow {
background-color: yellow;
}
.colorGray {
background-color: gray;
}
.colorRed {
background-color: red;
}
.colorGreen {
background-color: green;
}
.colorWhite {
background-color: white;
}
#main {
margin: 0 auto;
width: 325px;
text-align: center;
background-color: gray;
}
.row {
width: 300px;
padding: 10px;
border: 1px solid black;
display: block;
}
.hideButton, .mainText, .deleteButton {
margin: 0 auto;
padding: 10px;
border: 1px solid black;
display: inline;
}
.btn {
}
</style>
</head>
<body>
<div id="main">
<div class="AddBtn btn">Add</div>
<input type="text" id="txtBox" name="text till ruta" />
</div>
<script>
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
So far everything works as I want it to do. But when I click on "<" it will go in to this function and find all tags with the hideButton class in it.
The first click it won't find anything, but the second time it will find the "<" value and an alert window will popup and show the value. Here is where I
get lost and can't get it to work. When you click the the third time it will
loop or whatever to call it - anyway it will show the alert window 2 times and
then if you repeat the same click it will do the same thing 3 times and so it goes.
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
for (var j = 0; j < hideButton.length; j++) {
hideBtn = hideButton[j];
hideBtn.addEventListener('click', function () {
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}, false);
}
}
}, false);
}
}
window.onload = addListeners;
</script>
</body>
</html>
The goal with this exercise is that
when you click add button add the text from the input field and add that text to the new row.
and "<" shall hide the row and change it to ">" to show it again
and "X" shall just delete the row.
But what I need help with is finding the value part that I mentioned above.
Here is my rework of your javascript. I explained my solution in your comment, but it may be a bit more clear if illustrated.
In the addListeners function, I removed the hideOrShow call as it shouldn't be called in the add button.
Next, I removed the for loop in the hideOrShow method as you really are only after the caller. I also removed the addEventListener call in the same method as you already have an event listener on that element, so there's no need to add one again.
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
//hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}
}, false);
}
}
window.onload = addListeners;

how to generate tinymce to ajax generated textarea

I have an image multi-uploader script which also each item uploaded was preview 1st before it submitted and each images has its following textarea which are also generated by JavaScript. I want to use the tinymce editor to each textarea generated by the ajax.
Here is my script:
function fileQueueError(file, errorCode, message) {
try {
var imageName = "error.gif";
var errorName = "";
if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
errorName = "You have attempted to queue too many files.";
}
if (errorName !== "") {
alert(errorName);
return;
}
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
imageName = "zerobyte.gif";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
imageName = "toobig.gif";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
default:
alert(message);
break;
}
addImage("images/" + imageName);
} catch (ex) {
this.debug(ex);
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if (numFilesQueued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function uploadProgress(file, bytesLoaded) {
try {
var percent = Math.ceil((bytesLoaded / file.size) * 100);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setProgress(percent);
if (percent === 100) {
progress.setStatus("Creating thumbnail...");
progress.toggleCancel(false, this);
} else {
progress.setStatus("Uploading...");
progress.toggleCancel(true, this);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadSuccess(file, serverData) {
try {
var progress = new FileProgress(file, this.customSettings.upload_target);
if (serverData.substring(0, 7) === "FILEID:") {
addRow("tableID","thumbnail.php?id=" + serverData.substring(7),file.name);
//setup();
//generateTinyMCE('itemdescription[]');
progress.setStatus("Thumbnail Created.");
progress.toggleCancel(false);
} else {
addImage("images/error.gif");
progress.setStatus("Error.");
progress.toggleCancel(false);
alert(serverData);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadComplete(file) {
try {
/* I want the next upload to continue automatically so I'll call startUpload here */
if (this.getStats().files_queued > 0) {
this.startUpload();
} else {
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setComplete();
progress.setStatus("All images received.");
progress.toggleCancel(false);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadError(file, errorCode, message) {
var imageName = "error.gif";
var progress;
try {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Cancelled");
progress.toggleCancel(false);
}
catch (ex1) {
this.debug(ex1);
}
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Stopped");
progress.toggleCancel(true);
}
catch (ex2) {
this.debug(ex2);
}
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
imageName = "uploadlimit.gif";
break;
default:
alert(message);
break;
}
addImage("images/" + imageName);
} catch (ex3) {
this.debug(ex3);
}
}
function addRow(tableID,src,filename)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
rowCount + 1;
row.id = "row"+rowCount;
var cell0 = row.insertCell(0);
cell0.innerHTML = rowCount;
cell0.style.background = "#FFFFFF";
var cell1 = row.insertCell(1);
cell1.align = "center";
cell1.style.background = "#FFFFFF";
var imahe = document.createElement("img");
imahe.setAttribute("src",src);
var hidden = document.createElement("input");
hidden.setAttribute("type","hidden");
hidden.setAttribute("name","filename[]");
hidden.setAttribute("value",filename);
/*var hidden2 = document.createElement("input");
hidden2.setAttribute("type","hidden");
hidden2.setAttribute("name","filename[]");
hidden2.setAttribute("value",filename);
cell1.appendChild(hidden2);*/
cell1.appendChild(hidden);
cell1.appendChild(imahe);
var cell2 = row.insertCell(2);
cell2.align = "left";
cell2.valign = "top";
cell2.style.background = "#FFFFFF";
//tr1.appendChild(td1);
var div2 = document.createElement("div");
div2.style.padding ="0 0 0 10px";
div2.style.width = "400px";
var alink = document.createElement("a");
//alink.style.margin="40px 0 0 0";
alink.href ="#";
alink.innerHTML ="Cancel";
alink.onclick= function () {
document.getElementById(row.id).style.display='none';
document.getElementById(textfield.id).disabled='disabled';
};
var div = document.createElement("div");
div.style.margin="10px 0";
div.appendChild(alink);
var textfield = document.createElement("input");
textfield.id = "file"+rowCount;
textfield.type = "text";
textfield.name = "itemname[]";
textfield.style.margin = "10px 0";
textfield.style.width = "400px";
textfield.value = "Item Name";
textfield.onclick= function(){
//textfield.value="";
if(textfield.value=="Item Name")
textfield.value="";
if(desc.innerHTML=="")
desc.innerHTML ="Item Description";
if(price.value=="")
price.value="Item Price";
}
var desc = document.createElement("textarea");
desc.name = "itemdescription[]";
desc.cols = "80";
desc.rows = "4";
desc.innerHTML = "Item Description";
desc.onclick = function(){
if(desc.innerHTML== "Item Description")
desc.innerHTML = "";
if(textfield.value=="Item name" || textfield.value=="")
textfield.value="Item Name";
if(price.value=="")
price.value="Item Price";
}
var price = document.createElement("input");
price.id = "file"+rowCount;
price.type = "text";
price.name = "itemprice[]";
price.style.margin = "10px 0";
price.style.width = "400px";
price.value = "Item Price";
price.onclick= function(){
if(price.value=="Item Price")
price.value="";
if(desc.innerHTML=="")
desc.innerHTML ="Item Description";
if(textfield.value=="")
textfield.value="Item Name";
}
var span = document.createElement("span");
span.innerHTML = "View";
span.style.width = "auto";
span.style.padding = "10px 0";
var view = document.createElement("input");
view.id = "file"+rowCount;
view.type = "checkbox";
view.name = "publicview[]";
view.value = "y";
view.checked = "checked";
var div3 = document.createElement("div");
div3.appendChild(span);
div3.appendChild(view);
var div4 = document.createElement("div");
div4.style.padding = "10px 0";
var span2 = document.createElement("span");
span2.innerHTML = "Default Display";
span2.style.width = "auto";
span2.style.padding = "10px 0";
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "setdefault";
radio.value = "y";
div4.appendChild(span2);
div4.appendChild(radio);
div2.appendChild(div);
//div2.appendChild(label);
//div2.appendChild(table);
div2.appendChild(textfield);
div2.appendChild(desc);
div2.appendChild(price);
div2.appendChild(div3);
div2.appendChild(div4);
cell2.appendChild(div2);
}
function addImage(src,val_id) {
var newImg = document.createElement("img");
newImg.style.margin = "5px 50px 5px 5px";
newImg.style.display= "inline";
newImg.id=val_id;
document.getElementById("thumbnails").appendChild(newImg);
if (newImg.filters) {
try {
newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
}
} else {
newImg.style.opacity = 0;
}
newImg.onload = function () {
fadeIn(newImg, 0);
};
newImg.src = src;
}
function fadeIn(element, opacity) {
var reduceOpacityBy = 5;
var rate = 30; // 15 fps
if (opacity < 100) {
opacity += reduceOpacityBy;
if (opacity > 100) {
opacity = 100;
}
if (element.filters) {
try {
element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
}
} else {
element.style.opacity = opacity / 100;
}
}
if (opacity < 100) {
setTimeout(function () {
fadeIn(element, opacity);
}, rate);
}
}
/* ******************************************
* FileProgress Object
* Control object for displaying file info
* ****************************************** */
function FileProgress(file, targetID) {
this.fileProgressID = "divFileProgress";
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
fadeIn(this.fileProgressWrapper, 0);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
}
this.height = this.fileProgressWrapper.offsetHeight;
}
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.className = "progressContainer blue";
this.fileProgressElement.childNodes[3].className = "progressBarComplete";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfuploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfuploadInstance.cancelUpload(fileID);
return false;
};
}
};
I am using a swfuploader and I just added a input fields and a textarea when it preview the images which ready to be uploaded.
And from my HTML I have this script:
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "../we_modules/upload.php", // Relative to the SWF file or absolute
post_params: {"PHPSESSID": "<?php echo session_id(); ?>"},
// File Upload Settings
file_size_limit : "20 MB", // 2MB
file_types : "*.*",
//file_types : "",
file_types_description : "jpg",
file_upload_limit : "0",
file_queue_limit : "0",
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
//file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
// Button Settings
button_image_url : "../we_modules/images/SmallSpyGlassWithTransperancy_17x18.png", // Relative to the SWF file
button_placeholder_id : "spanButtonPlaceholder",
button_width: 180,
button_height: 18,
button_text : '<span class="button">Select Files<span class="buttonSmall">(2 MB Max)</span></span>',
button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt;cursor:pointer } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 0,
button_text_left_padding: 18,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
// Flash Settings
flash_url : "../swfupload/swfupload.swf",
custom_settings : {
upload_target : "divFileProgressContainer"
},
// Debug Settings
debug: false
});
};
</script>
Where should I put on the tinymce function as you mention below?
Taken directly from the TinyMCE documentation:
<script type="text/javascript" src="<your installation path>/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form method="post" action="somepage">
<textarea name="content" style="width:100%">
</textarea>
</form>
Please read the documentation for basic questions like this.
If you get stuck or need help after you've done that, provide a clear explanation of your problem (and sample code if possible) so that we can help you.
Edit:
Alright, I've attempted a solution to the problem. The following code loads 20 images and textareas dynamically and then turns the textareas into TinyMCE editors (I hope you don't mind the jQuery):
<html>
<head>
<script src="TinyMCE/jscripts/tiny_mce/tiny_mce.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
img { height: 100px; display: block;}
li { border: 1px solid black; margin: 1em; padding: 1em; }
#message { position: fixed; top: 0; left: 50%; margin-left: -100px; width: 200px; text-align: center; background-color: white; border: 1px solid black;}
</style>
</head>
<body>
<ul>
</ul>
<div id="message">Loading...</div>
<script>
$(function(){
var numImages = 20;
for (var i = 0; i < numImages; i++) {
// Create an img element with a random image
var img = $('<img />').attr('src', randomXKCD);
// Attach a callback to the image's load event
img.load(function(){
numImages--;
if (numImages === 0) {
// When all the images have loaded,
// turn the textareas into tinyMCE editors
tinyMCE.init({
mode: 'textareas',
theme: 'simple',
oninit: function(){$('#message').hide()}
});
}
});
// Add the image and a textarea to the document.
$('ul').append(
$('<li />')
.append(img)
.append('<textarea />')
);
}
// helper function to get a random image.
function randomXKCD() {
var xkcds = [
'http://imgs.xkcd.com/comics/barrel_mommies.jpg',
'http://imgs.xkcd.com/comics/su_doku.jpg',
'http://imgs.xkcd.com/comics/linux_user_at_best_buy.png',
'http://imgs.xkcd.com/comics/commented.png',
'http://imgs.xkcd.com/comics/typewriter.png',
'http://imgs.xkcd.com/comics/pirate_bay.png',
'http://imgs.xkcd.com/comics/quirky_girls.png',
'http://imgs.xkcd.com/comics/firefly.jpg',
'http://imgs.xkcd.com/comics/kepler.jpg',
'http://imgs.xkcd.com/comics/centrifugal_force.png',
'http://imgs.xkcd.com/comics/trebuchet.png',
'http://imgs.xkcd.com/comics/egg_drop_failure.png',
'http://imgs.xkcd.com/comics/too_old_for_this_shit.png',
'http://imgs.xkcd.com/comics/2008_christmas_special.png',
'http://imgs.xkcd.com/comics/braille.png',
'http://imgs.xkcd.com/comics/impostor.png',
'http://imgs.xkcd.com/comics/not_enough_work.png'
];
return xkcds[Math.floor(Math.random() * xkcds.length)];
}
});
</script>
</body>
</html>

Categories

Resources