Javascript is not working after adding some functions - javascript

I was working on project which required to change background color of webpage when user hover mouse on a textfield and whole webpage theme must change when mouse pointer is on that textfield. It worked well but when I added a submit button and made a function to change its properties on mouse over and on mouse out, whole Javascript code stopped working!
<!DOCTYPE html>
<?php
function redirect($url){
ob_start();
header('Location: '.$url);
ob_end_flush();
die();
}
$error = "";
$myurl = $_SERVER['REQUEST_URI'];
if (isset($_GET['name'])) {
$name = $_GET['name'];
} else {
$name = "";
}
//$name = $_GET["name1"];
$name = trim($name);
if(empty($name)){
$error="";
}else{
echo $myurl;
}
?>
<html>
<head>
<title>We Wish</title>
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Poppins&display=swap');
#import url('https://fonts.googleapis.com/css?family=Comfortaa:700&display=swap');
body{
background-color: #1a1a1a;
}
input{
background-color: transparent;
border-radius: 50px;
border: 1.5px solid white;
}
#pallete{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
#nametf{
width: 200px;
height: 20px;
padding: 5px 10px;
color: white;
font-size: 15px;
font-family: 'Comfortaa', cursive;
}
#nametf:hover{
border: 1.5px solid #1a1a1a;
}
#btn{
color: white;
font-family: 'Comfortaa', cursive;
background-color: transparent;
border: 1.5px solid white;
border-radius: 50px;
padding: 9px 20px 8px 20px;
margin-top: 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 10px;
cursor: pointer;
transition-duration: 0s;
}
#btn:hover{
color: #1a1a1a;
background-color: cyan;
border-color: cyan;
box-shadow: 0px 0px 15px cyan;
}
</style>
</head>
<body>
<center>
<div id="pallete">
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onmouseover="bgChange('white','#1a1a1a')" onmouseout="bgChange('#1a1a1a','white')" onchange="widen()" value="" required>
</form>
<span>
<input type="submit" name="submit" id="btn" value="CREATE" onmouseover="glow('on')" onmouseout="glow('off')">
</span>
</div>
</center>
</body>
<script type="text/javascript">
var nametf = document.getElementById('nametf');
function bgChange(bg,color){
document.body.style.background = bg;
nametf.style.color = color;
var btn = document.getElementById('btn');
if(bg=='white'){
//btn.style.transition-duration = "0s";
btn.style.border = "1.5px solid #1a1a1a";
btn.style.color = "#1a1a1a";
} else {
//btn.style.transition-duration = "0s";
btn.style.border = "1.5px solid white";
btn.style.color = "white";
}
}
function widen(){
var value = nametf.value;
if(value.length > 17){
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
function glow(mode){
if(mode=='on'){
btn.style.transition-duration = "0.4s";
btn.style.color = "#1a1a1a";
btn.style.background-color = "cyan";
btn.style.border-color = "cyan";
btn.style.box-shadow = "0px 0px 15px cyan";
} else {
btn.style.transition-duration = "0.4s";
btn.style.color = "white";
btn.style.background-color = "transparent";
btn.style.border-color = "white";
btn.style.box-shadow = "0px 0px 0px transparent";
}
}
</script>
</html>
I even tried alerting a message without any function but still it didn't work!!

btn.style.transition-duration is going to be the first place where you're getting issues. you can't have a dash in a property name just bare like that. Try changing those properties with dashes in them in another way
btn.style['transition-duration'] may work, I'm not 100% sure, but I am sure that the dashes are creating basically a syntax error.

You are assigning values to property that has hyphen in them ( - ). In Javascript, this is not allowed.
You should change the property assignement that has hyphen ( btn.style.transition-duration = "0.4s"; for example) to use CamelCase
instead.
btn.style.transitionDuration = "0.4s";
This might fix one of your problems. There might be more, but we can't be sure until you tell us if there is any error in the JS console and what they are.

Related

javascript on a webpage displaying text wrongly

I have JS code on a webpage that loads questions in from mysql db and displays the text . What happens is that it cuts off words at the end of the line and continues the word on the next line at the start. So all text across the screen starts/ends at the same point.
This seems to be the code where it displays the text.
For example the text will look like at the end of a line 'cont' and then on next line at the start 'inue'.
How do i fix this?
var questions = <?=$questions;?>;
// Initialize variables
//------------------------------------------------------------------
var tags;
var tagsClass = '';
var liTagsid = [];
var correctAns = 0;
var isscorrect = 0;
var quizPage = 1;
var currentIndex = 0;
var currentQuestion = questions[currentIndex];
var prevousQuestion;
var previousIndex = 0;
var ulTag = document.getElementsByClassName('ulclass')[0];
var button = document.getElementById('submit');
var questionTitle = document.getElementById('question');
//save class name so it can be reused easily
//if I want to change it, I have to change it one place
var classHighlight = 'selected';
// Display Answers and hightlight selected item
//------------------------------------------------------------------
function showQuestions (){
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
if (currentIndex != 0) {
// create again submit button only for next pages
ulTag.innerHTML ='';
button.innerHTML = 'Submit';
button.className = 'submit';
button.id = 'submit';
if(quizPage<=questions.length){
//update the number of questions displayed
document.getElementById('quizNumber').innerHTML = quizPage;
}
}
//Display Results in the final page
if (currentIndex == (questions.length)) {
ulTag.innerHTML = '';
document.getElementById('question').innerHTML = '';
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
showResults();
return
}
questionTitle.innerHTML = "Question No:" + quizPage + " "+currentQuestion.question.category_name +"<br/>"+ currentQuestion.question.text;
if(currentQuestion.question.filename !== ''){
var br = document.createElement('br');
questionTitle .appendChild(br);
var img = document.createElement('img');
img.src = currentQuestion.question.filename;
img.className = 'imagecenter';
img.width = 750;
img.height = 350;
questionTitle .appendChild(img);
}
// create a for loop to generate the options and display them in the page
for (var i = 0; i < currentQuestion.options.length; i++) {
// creating options
var newAns = document.createElement('li');
newAns.id = 'ans'+ (i+1);
newAns.className = "notSelected listyle";
var textAns = document.createTextNode(currentQuestion.options[i].optiontext);
newAns.appendChild(textAns);
if(currentQuestion.options[i].file !== ''){
var br = document.createElement('br');
newAns .appendChild(br);
var img1 = document.createElement('img');
img1.src = currentQuestion.options[i].file;
img1.className = 'optionimg';
img1.width = 250;
img1.height = 250;
newAns .appendChild(img1);
newAns .appendChild(br);
}
var addNewAnsHere = document.getElementById('options');
addNewAnsHere.appendChild(newAns);
}
//.click() will return the result of $('.notSelected')
var $liTags = $('.notSelected').click(function(list) {
list.preventDefault();
//run removeClass on every element
//if the elements are not static, you might want to rerun $('.notSelected')
//instead of the saved $litTags
$liTags.removeClass(classHighlight);
//add the class to the currently clicked element (this)
$(this).addClass(classHighlight);
//get id name of clicked answer
for (var i = 0; i < currentQuestion.options.length ; i++) {
// console.log(liTagsid[i]);
if($liTags[i].className == "notSelected listyle selected"){
//store information to check answer
tags = $liTags[i].id;
// tagsClass = $LiTags.className;
tagsClassName = $liTags[i];
}
}
});
//check answer once it has been submitted
button.onclick = function (){
if(button.id == 'submit'){
button.className = 'buttonload';
button.innerHTML = '<i class="fa fa-spinner fa-spin"></i>Loading';
}
setTimeout(function() { checkAnswer(); }, 100);
};
}
//self calling function
showQuestions();
The website is on my local now but i can upload a screenimage if need be and the whole code of the webpage. Or is the issue in html?
edit: here is html/css code
<style>
/*========================================================
Quiz Section
========================================================*/
/*styling quiz area*/
.main {
background-color: white;
margin: 0 auto;
margin-top: 30px;
padding: 30px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
/*white-space: nowrap;*/
}
/*Editing the number of questions*/
.spanclass {
font-size: x-large;
}
#pages{
border: 3px solid;
display: inline-flex;
border-radius: 0.5em;
float: right;
}
#question{
word-break: break-all;
}
/*format text*/
p {
text-align: left;
font-size: x-large;
padding: 10px 10px 0;
}
.optionimg{
border: 2px solid black;
border-radius: 1.5em;
}
/*Form area width*/
/*formatting answers*/
.listyle {
list-style-type: none;
text-align: left;
background-color: transparent;
margin: 10px 5px;
padding: 5px 10px;
border: 1px solid lightgray;
border-radius: 0.5em;
font-weight: normal;
font-size: x-large;
display: inline-grid;
width: 48%;
height: 300px;
overflow: auto;
}
.listyle:hover {
background: #ECEEF0;
cursor: pointer;
}
/*Change effect of question when the questions is selected*/
.selected, .selected:hover {
background: #FFDEAD;
}
/*change correct answer background*/
.correct, .correct:hover {
background: #9ACD32;
color: white;
}
/*change wrong answer background*/
.wrong, .wrong:hover {
background: #db3c3c;
color: white;
}
/*========================================================
Submit Button
========================================================*/
.main button {
text-transform: uppercase;
width: 20%;
border: none;
padding: 15px;
color: #FFFFFF;
}
.submit:hover, .submit:active, .submit:focus {
background: #43A047;
}
.submit {
background: #4CAF50;
min-width: 120px;
}
/*next question button*/
.next {
background: #fa994a;
min-width: 120px;
}
.next:hover, .next:active, .next:focus {
background: #e38a42;
}
.restart {
background-color:
}
/*========================================================
Results
========================================================*/
.circle{
position: relative;
margin: 0 auto;
width: 200px;
height: 200px;
background: #bdc3c7;
-webkit-border-radius: 100px;
-moz-border-radius: 100px;
border-radius: 100px;
overflow: hidden;
}
.fill{
position: absolute;
bottom: 0;
width: 100%;
height: 80%;
background: #31a2ac;
}
.score {
position: absolute;
width: 100%;
top: 1.7em;
text-align: center;
font-family: Arial, sans-serif;
color: #fff;
font-size: 40pt;
line-height: 0;
font-weight: normal;
}
.circle p {
margin: 400px;
}
/*========================================================
Confeeti Effect
========================================================*/
canvas{
position:absolute;
left:0;
top:11em;
z-index:0;
border:0px solid #000;
}
.imagecenter{
display: block;
margin: 0 auto;
}
.buttonload {
background-color: #04AA6D; /* Green background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
#media only screen and (max-width: 900px){
.listyle {
width: 100% !important;
height: auto !important;
}
.imagecenter {
width: 100% !important;
}
.listyle img{
width: inherit !important;
height: unset !important;
}
.ulclass
{
padding:0px !important;
}
}
</style>
<!-- Main page -->
<div class="main">
<!-- Number of Question -->
<div class="wrapper" id="pages">
<span class="spanclass" id="quizNumber">1</span><span class="spanclass">/<?=$count?></span>
</div>
<!-- Quiz Question -->
<div class="quiz-questions" id="display-area">
<p id="question"></p>
<ul class="ulclass" id="options">
</ul>
<div id="quiz-results" class="text-center">
<button type="button" name="button" class="submit" id="submit">Submit</button>
</div>
</div>
</div>
<canvas id="canvas"></canvas>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
I'm guessing that #question{ word-break: break-all; } is probably the culprit then? –
CB..yes that fixed it:)

How would I use localStorage to remember button click in PugJS?

This is what I have in my .pug file that I need the website to remember. If a user clicks the Large button then the website should remember that when the website is refreshed.
.scaling
scalingButton(onclick='body.style.fontSize = "1.0em"')='Normal'
scalingButton(onclick='body.style.fontSize = "1.2em"')='Medium'
scalingButton(onclick='body.style.fontSize = "1.5em"')='Large'
and here is what I have in the .css file for these buttons:
.scaling{
text-align: end;
position: fixed;
margin: 150px;
margin-right: 0%;
margin-bottom: 5%;
bottom: 0px;
right :20%;
}
scalingButton{
background-color: white;
padding: 5px 10px;
margin-top: 600px;
font-weight: bold;
border-radius: 3px;
border: 2px solid black;
filter: drop-shadow(2px 2px 2px black);
transition: 0.3s;
}
scalingButton:hover{
background-color: grey;
cursor: pointer;
}
You need to write a function that stores value in localStorage and when page is loaded (DOMContentLoaded ) you need to check localStorage, if localStorage has a font-size then you can apply it to the body.
script:
function changeFontSize(size) {
let fontSize = size + "em"
body.style.fontSize = fontSize;
localStorage.setItem('font-size', fontSize);
}
document.addEventListener("DOMContentLoaded", function(event) {
let fontSize = localStorage.getItem('font-size');
if(fontSize) {
body.style.fontSize = fontSize;
}
});
template
.scaling
scalingButton(onclick="changeFontSize('1.0em')")='Normal'
scalingButton(onclick="changeFontSize('1.2em')")='Medium'
scalingButton(onclick="changeFontSize('1.5em')")='Large'

localStorage does not save/show items

I do my ToDo list. (I learn vanilla JS). And I have some problem with saving some items to localStorage. When I use Google chrome(F12), I see undefiend. Maybe, I do not save correctly to localStorage. I tried to change var task to array, but it does not help. Pleas, show me my mistakes. I know, my code must be rewritten, it is my first code on JS. P.s. in console (in stackOverflow) I have that error
{
"message": "Uncaught SyntaxError: Unexpected identifier",
"filename": "https://stacksnippets.net/js",
"lineno": 348,
"colno": 6
}
but in my browser not.
var task = document.querySelector("ul");
var forTask;
function toLocal(){
forTask = task.innerHTML;
localStorage.setItem("forLocal",forTask);
}
function newElement(newChild) {
let btnDel= document.createElement("button");
btnDel.className = "fa fa-trash-o";
let myEd = document.getElementById("myEdit");
let spanClose1 = document.getElementsByClassName("close1")[0];
let spanRedact = document.getElementsByClassName("redact")[0];
let myDel = document.getElementById("myDelete");
let spanClose = document.getElementsByClassName("close")[0];
let spanYes = document.getElementsByClassName("yes")[0];
//create button
let divWithBut = document.createElement("div");
divWithBut.className = "forButt";
let btnRedact = document.createElement("button");
btnRedact.className = "fa fa-pencil";
//redact but
btnRedact.onclick = function(){
myEd.style.display = "block";
let editText = document.getElementById("editText");
let divWithText = divWithBut.parentElement.getElementsByClassName("todoPost")[0];
editText.value = divWithText.innerHTML;
editText.currentTarget;
spanRedact.onclick = function(){
divWithText.textContent = editText.value;
divWithText.className = "todoPost";
myEd.style.display = "none";
};
spanClose1.onclick = function() {
myEd.style.display = "none";
};
}
/*************************** */
/*done but*/
let doneBut = document.createElement("button");
doneBut.className = "fa fa-check-circle-o";
doneBut.onclick = function(){
let divWithText = divWithBut.parentElement.getElementsByClassName("todoPost")[0];
divWithText.classList.toggle("checked");
}
/******************* */
divWithBut.appendChild(btnRedact);
divWithBut.appendChild(doneBut);
divWithBut.appendChild(btnDel);
/******************/
//for index
let indexDiv = document.createElement("div");
indexDiv.className = "indexDiv";
let numbInd = 1;
indexDiv.innerHTML = numbInd;
/*********************************** */
//create arrow
let divWithArrow = document.createElement("div");
divWithArrow.className = "myArrow";
let arrowUP = document.createElement("i");
arrowUP.className = "fa fa-chevron-up";
let arrowDown = document.createElement("i");
arrowDown.className = "fa fa-chevron-down";
divWithArrow.appendChild(arrowUP);
divWithArrow.appendChild(arrowDown);
//for date
let date = new Date();
let curr_date = date.getDate();
let curr_month = date.getMonth()+1;
let curr_year = date.getFullYear();
let curr_hour = date.getHours();
let curr_minutes = date.getMinutes();
let d = (curr_date + "." + curr_month + "." + curr_year+"<br>"+curr_hour+":"+curr_minutes);
let divTime = document.createElement("div");
divTime.style.textAlign = "center";;
divTime.innerHTML = d;
//***************************/
let div1 = document.createElement("div");
div1.className = "timeComent";
let myli = document.createElement("li");
myli.className = "todoPost";
let addField = document.getElementById("addField").value;
task = document.createTextNode(addField);
myli.appendChild(task);
div1.appendChild(divTime);
div1.appendChild(indexDiv);
div1.appendChild(divWithArrow);
div1.appendChild(myli);
divWithBut.style.display = "flex";
div1.appendChild(divWithBut);
if (addField === '') {
alert("You must write something!");
} else {
document.getElementById("forToDo").appendChild(div1);
toLocal();
}
document.getElementById("addField").value = "";
//delete but
btnDel.onclick = function(){
myDel.style.display = "block";
spanClose.onclick = function() {
myDel.style.display = "none";
};
spanYes.onclick = function() {
myDel.style.display = "none";
div1.remove();
};
}
toLocal();
}
if(localStorage.getItem("forLocal")){
task.innerHTML = localStorage.getItem("forLocal");
}
*{
margin: 0;
padding: 0;
}
header{
width: 100%;
display: flex;
align-items: center;
align-content: center;
justify-content: center;
overflow: auto;
}
.firstBar{
width: 100%;
display: flex;
align-items: center;
align-content: center;
justify-content: center;
overflow: auto;
}
.indexDiv{
font-style: normal;
text-align: center;
color: #fff;
width: 15px;
height: 20px;
margin: 10px;
background-color: #888;
}
.fafaArrow{
font-size: 24px;
color: #000;
}
.timeComent{
margin-top: 15px;
margin-bottom: 15px;
display: flex;
justify-content:center;
align-items: center;
}
.numberpost{
padding: 5px;
color: rgb(255, 255, 255);
background: rgb(141, 112, 112);
}
.todoPost{
background-color: #eee;
width: 50%;
margin: 5px;
overflow: auto;
text-align: justify;
}
.shadow {
background: rgba(102, 102, 102, 0.5);
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
display: none;
}
.window {
width: 300px;
height: 50px;
text-align: center;
padding: 15px;
border: 3px solid #0000cc;
border-radius: 10px;
color: #0000cc;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: #fff;
}
.shadow:target {display: block;}
.redact {
display: inline-block;
border: 1px solid #0000cc;
color: #0000cc;
margin: 10px;
text-decoration: none;
background: #f2f2f2;
font-size: 14pt;
cursor:pointer;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.redact:hover {
background-color: #68f462;
color: white;}
.close{
display: inline-block;
border: 1px solid #0000cc;
color: #0000cc;
margin: 10px;
text-decoration: none;
background: #f2f2f2;
font-size: 14pt;
cursor:pointer;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover{
background-color: #f44336;
color: white;
}
/* Style the close button */
.close3 {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.yes {
display: inline-block;
border: 1px solid #0000cc;
color: #0000cc;
margin: 10px;
text-decoration: none;
background: #f2f2f2;
font-size: 14pt;
cursor:pointer;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.yes:hover{
background-color: #68f462;
color: white;
}
.close1{
display: inline-block;
border: 1px solid #0000cc;
color: #0000cc;
margin: 10px;
text-decoration: none;
background: #f2f2f2;
font-size: 14pt;
cursor:pointer;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close1:hover{
background-color: #f44336;
color: white;
}
/* When clicked on, add a background color and strike out text */
div li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
div li.checked::before {
content: '';
position: absolute;
border-color: #fff;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
<!DOCTYPE html>
<html>
<head>
<title>TO DO List</title>
<link rel="stylesheet" type="text/css" href="styles/style.css" >
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<header>
<input id="addField" type="text" size="70%" placeholder="Task" name="Task">
<button type="button" onclick="newElement()">Add</button>
</header>
<div>
<div class="firstBar">
<div class="fafaArrow">
<i class="fa fa-caret-up" ></i>
<i class="fa fa-caret-down"></i>
<input class="inptxt" type="text" size="50%" name="Task">
<i class="fa fa-filter"></i>
</div>
</div>
</div>
<ul id="forToDo" >
</ul>
<div id="myDelete" class="shadow">
<div class="window">Delete item?<br>
<span class="yes">Yes</span>
<span class="close">No</span>
</div>
</div>
<div id="myEdit" class="shadow">
<div class="window">
Edit text?<br>
<label>
<textarea id="editText"></textarea>
</label>
<span class="redact">Save</span>
<span class="close1">Cancel</span>
</div>
</div>
<script src="js/script2.js"></script>
</body>
</html>
When you add an element to the page, at a certain point you do this
task = document.createTextNode(addField);
Since task is a global variable (you declared it at the top), you're overshadowing it with the TextNode you're creating, so that when you then call toLocal and you do
forTask = task.innerHTML;
task has no innerHTML attribute, so it returns undefined.
Also, for some reason, you call toLocal again at the end of newElement. It's not the problem but it's something you may want to think about. I'm not sure it's what you want.
#TakayashiHarano gave a couple of hints to solve this, but I'm not sure what you want is just to have the latest element in the local storage. So I would re-write toLocal so that it takes a string (the text of the item) as input, writes it at the end of a JSON array (already populated with what was in the local storage previously), and puts the array back in local storage.
function toLocal(toAdd) {
let storage = localStorage.getItem('forLocal');
if (storage === null) {
storage = [];
} else {
storage = JSON.parse(storage);
}
storage.push(toAdd);
localStorage.setItem('forLocal', JSON.stringify(storage));
}
Then you should modify the part of the code that reads the local storage (the one at the end) to basically simulate adding a new item as you would do when creating a new task, but for each item in the parsed JSON coming from local storage.
To be fair, your code needs a good dose of rewriting to achieve this, so I'll just leave you with this as an exercise.
The following changes are needed.
1 - Set up two variables separably for the following task variable.
var task = document.querySelector("ul");
task = document.createTextNode(addField);
For example, "ulElement" for the first one, and "task" for the second one.
This is to prevent to override the previously defined value.
2 - Move the timing for obtaining the ul element and load localStorage.
function onReady() {
ulElement = document.querySelector("ul");
if(localStorage.getItem("forLocal")){
ulElement.innerHTML = localStorage.getItem("forLocal");
}
}
window.addEventListener('DOMContentLoaded', onReady, true);
To ensure the element existence, document.querySelector() should be called after the DOMContentLoaded event fired.
https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
3 - Delete toLocal(); in the end of the newElement() function.
As far as my testing code, there is no need this statement.

I am trying to change the style of a html link with javascript functions. Why does my code not work?

In the console I get these types of errors:
ReferenceError: invalid assignment left-hand side
ReferenceError: changeButtonOnMouseOver is not defined
Here is my code:
<!DOCTYPE html>
<html>
<body>
<br />
<br />
<br />
<br />
<script>
function changeButtonOnMouseOver()
{
document.getElementById("btn").style.background-color = "#00806f";
document.getElementById("btn").style.cursor = "pointer";
}
function changeButtonOnClick()
{
document.getElementById("btn").style.box-shadow = "none";
document.getElementById("btn").style.top = "5px";
}
function changeButtonOnMouseOut()
{
document.getElementById("btn").style.border-radius = "15px";
document.getElementById("btn").style.background-color = "#009682";
document.getElementById("btn").style.box-shadow = "0 5px 0 #00332c";
document.getElementById("btn").style.color = "white";
document.getElementById("btn").style.cursor = "auto";
document.getElementById("btn").style.padding = "1em 1.5em";
document.getElementById("btn").style.position = "relative";
document.getElementById("btn").style.text-align = "center";
document.getElementById("btn").style.text-decoration = "none";
document.getElementById("btn").style.font-size = "x-large";
document.getElementById("btn").style.font-weight = "800";
document.getElementById("btn").style.outline = "none";
document.getElementById("btn").style.border = "none";
}
</script>
<a id="btn" href="#" onmouseover="changeButtonOnMouseOver()" onclick="changeButtonOnClick()" onmouseout="changeButtonOnMouseOut()"
style="border-radius: 15px;
background-color: #009682;
box-shadow: 0 5px 0 #00332c;
color: white;
padding: 1em 1.5em;
position: relative;
text-align: center;
text-decoration: none;
font-size: x-large;
font-weight: 800;
outline: none;
border: none;" >
Zur Anmeldung</a>
</body>
</html>
I made the link look like a button and I want to change the style with javascript functions for onmouseover or onclick events so it looks like you press a button when you click the link but I don't know why it doesn't work.
You should use camelCase property name for style in JavaScript:
function changeButtonOnMouseOver(){
document.getElementById("btn").style.backgroundColor = "#00806f";
document.getElementById("btn").style.cursor = "pointer";
}
function changeButtonOnClick(){
document.getElementById("btn").style.boxShadow = "none";
document.getElementById("btn").style.top = "5px";
}
function changeButtonOnMouseOut(){
document.getElementById("btn").style.borderRadius = "15px";
document.getElementById("btn").style.backgroundColor = "#009682";
document.getElementById("btn").style.boxShadow = "0 5px 0 #00332c";
document.getElementById("btn").style.color = "white";
document.getElementById("btn").style.cursor = "auto";
document.getElementById("btn").style.padding = "1em 1.5em";
document.getElementById("btn").style.position = "relative";
document.getElementById("btn").style.textAlign = "center";
document.getElementById("btn").style.textDecoration = "none";
document.getElementById("btn").style.fontSize = "x-large";
document.getElementById("btn").style.fontWeight = "800";
document.getElementById("btn").style.outline = "none";
document.getElementById("btn").style.border = "none";
}
<a id="btn" href="#" onmouseover="changeButtonOnMouseOver()" onclick="changeButtonOnClick()" onmouseout="changeButtonOnMouseOut()" style="border-radius: 15px;background-color: #009682;box-shadow: 0 5px 0 #00332c;color: white;padding: 1em 1.5em;position: relative;text-align: center;text-decoration: none;font-size: x-large;font-weight: 800;outline: none;border: none;">Zur Anmeldung</a>
You can achieve the same with pure CSS:
function changeButtonOnClick(){
document.getElementById("btn").style.boxShadow = "none";
document.getElementById("btn").style.top = "5px";
}
#btn, #btn:not(:hover){
border-radius: 15px;
background-color: #009682;
box-shadow: 0 5px 0 #00332c;
color: white;
padding: 1em 1.5em;
position: relative;
text-align: center;
text-decoration: none;
font-size: x-large;
font-weight: 800;
outline: none;
border: none;
}
#btn:hover{
background-color: #00806f;
cursor: pointer;
}
#btn:not( :hover ){
border-radius: 15px;
background-color: #009682;
box-shadow: 0 5px 0 #00332c;
color: white;
padding: 1em 1.5em;
position: relative;
text-align: center;
text-decoration: none;
font-size: x-large;
font-weight: 800;
outline: none;
border: none;
}
<a id="btn" href="#" onclick="changeButtonOnClick()" >
Zur Anmeldung</a>
You should camelCase for properties of style. Just remove - and make letter after - upperCase e.g background-color => backgroundColor. It will be same for for -. For example:
background-color => backgroundColor
border-left-width => borderLeftWidth
See An aside on variable naming rules.
You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character
You shouldn't use other characters because they may cause errors or be hard to understand for an international audience
Your script is loaded, before the id btn even exists in the DOM. You should put your script after declaring the id or set your script to be loaded after the DOM isnfully build
As you cannot add/edit the CSS and use classes. Can you create a new style node containing the required styles with JS?
const styleNode = document.createElement('style');
styleNode.type = 'text/css';
const cssStyles = `
#btn {
border-radius: 15px;
background-color: #009682;
box-shadow: 0 5px 0 #00332c;
color: white;
padding: 1em 1.5em;
position: relative;
text-align: center;
text-decoration: none;
font-size: x-large;
font-weight: 800;
outline: none;
border: none;
}
#btn:hover{
background-color: #00806f;
cursor: pointer;
}
#btn:active {
box-shadow: none;
top: 5px;
}
`;
styleNode.appendChild(document.createTextNode(cssStyles));
document.getElementsByTagName('head')[0].appendChild(styleNode);
<a id="btn" href="#">Zur Anmeldung</a>

Child div element managing

var arrlength;//////////////////////////////////////////////////////////////////
function opentextarea(borderColor) {
var arr = document.getElementsByClassName("myCustomTextarea");
arrlength=arr.length;
var goOut= 1;
Array.prototype.forEach.call(arr, function(el) {
if (el.style.backgroundColor!=='lightblue'){
goOut=0;
alert("Enter or delete the previus commnet!");
}
});
if (goOut===1){
//////////////
var comentwindow = document.getElementById("StatusID"); //StatusID
var d1 = new Date();
var d2= d1.toDateString();
var d3= d1.toLocaleTimeString();
var dateTimeUser = document.createTextNode(d2+" "+d3+" username");
//dateTimeUser.style.fontSize = "8px";
dateTimeUser.className = 'dateTimeUserClasN';
dateTimeUser.id = arrlength+"dateTimeUserID";
comentwindow.appendChild(dateTimeUser); /////////////////////////////////////////1
var input = document.createElement('textarea');
input.maxLength = 5000;
input.cols = 28;
input.rows = 5;
input.style.borderColor = borderColor;
input.className = 'myCustomTextarea';
var arr = document.getElementsByClassName("myCustomTextarea");
input.id = arrlength+"textarea";
//var comentwindow = document.getElementById("StatusID"); //StatusID
comentwindow.appendChild(input);//////////////////////////////////////////////////2
var ele = document.getElementById(arrlength+"buttonSE");
if(ele === null){
var buttonSE = document.createElement('button');
buttonSE.className = 'enterCommentBut';
buttonSE.id=arrlength+"buttonSE";
buttonSE.onclick = function() {
if(document.getElementById(arrlength+"textarea").value != ''){
document.getElementById(arrlength+"textarea").style.backgroundColor= "lightblue";
var e1 = document.getElementById('StatusID');
var e2 =(e1.children.length);
e1.removeChild(e1.children[e2-1]);
e1.removeChild(e1.children[e2-2]);
}else{
alert("It is not posible to enter empty comment.");
}
}
var SE = document.createTextNode("Enter");
buttonSE.appendChild(SE);
comentwindow.appendChild(buttonSE);/////////////////////////////////////////////3
}
var ele2 = document.getElementById(arrlength+"buttonSC");
if(ele2 === null){
var buttonSC = document.createElement('button');
buttonSC.className = 'clearCommentBut';
buttonSC.id=arrlength+"buttonSC";
buttonSC.onclick = function() {
var e1 = document.getElementById('StatusID');
var e2 =(e1.children.length);
var myNode = document.getElementById("StatusID");
while (myNode.lastChild) {
myNode.removeChild(myNode.lastChild);
}
};
var SC = document.createTextNode("Clear");
buttonSC.appendChild(SC);
comentwindow.appendChild(buttonSC);//////////////////////////////////////4
}
}
}
function createObject2(){
var e3 = document.getElementById("StatusID");
var e4 = document.getElementById("Status0ID");
var e5 = document.getElementById("Status2ID");
e3.style.display = 'block';
e4.style.display = 'block';
e5.style.display = 'block';
}
document.getElementById("clickMe2").onclick = createObject2;
function updateScroll(){
var element = document.getElementById("StatusID");
element.scrollTop = element.scrollHeight;
}
function ObjectRed(){
var borderColor= "red";
opentextarea(borderColor);
updateScroll();
}
document.getElementById("ObjectRed").onclick = ObjectRed;
function ObjectGreen(){
var borderColor= "green";
opentextarea(borderColor);
updateScroll();
}
document.getElementById("ObjectGreen").onclick = ObjectGreen;
*,
*::before,
*::after {
box-sizing: border-box;
}
div.Status0 {
position: absolute;
top: 15px;
width: 250px;
height:40px;
margin: 0;
padding: 1em;
font-size: 12px;
border: solid 1px #dfdfdf;
overflow-x: hidden;
overflow-y: visible;
background-color: white;
}
div.Status1 {
position: absolute;
top: 70px;
width: 250px;
height:700px;
margin: 0;
padding: 1em;
font-size: 12px;
border: solid 1px #dfdfdf;
overflow-x: hidden;
overflow-y: visible;
background-color: white;
}
div.Coment1{
float: left;
width: 130px;
height:100px;
margin: 0;
padding: 1em;
font-size: 12px;
/* height: 100%;
overflow: auto;*/
border: solid 1px #dfdfdf;
overflow-x: hidden;
overflow-y: visible;
background-color: yellow;
}
.content {
padding: 18px 0;
border-bottom: solid 2px #cfcfcf;
}
.myCustomTextarea {
border:0;
padding:1px;
font-size:1.0em;
font-family:"Times New Roman";
color:black;
border:solid 2px #ccc;
margin:0 0 4px;
width:215px;
height:50px;
-moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
box-shadow: inner 0 0 4px rgba(0, 0, 0, 0.2);
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.myCustomTextarea:focus {
resize: none;
border-radius: 5px;
outline: none !important;
}
.dateTimeUserClasN{
}
.startbutton{
position: absolute;
left: 270px;
top:20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom </title>
</head>
<body>
<div class="Status0" id="Status0ID" style="display: none">
<input type="button" id="ObjectRed" value="Problem" />
<input type="button" id="ObjectGreen" value="Okay" />
</div>
<div class="Status2" id="Status2ID" style="display: none">
<div class="Status1" id="StatusID" style="display: none"></div>
</div>
<input class =" startbutton" type="button" id="clickMe2" value="New object2" />
<script src="js/createObject.js"></script>
<link rel="stylesheet" href="css/styleIvan.css">
</body>
</html>
I have a "div" inside main "div". Status1 inside Status2. Status1 has a time date text, textarea and two buttons (enter and cancel).
When I call opentextarea function I get this 4 elements.
Below is this code for comments managing. The problem is that when i press on "cancel" button. It deletes all. But i would like to delete only last packet of
4 elements (last Status1 div). I need Status1 to be child of Status2. So when i press on cancel to delete only last child.
I can not make this work for me, so I am asking here for help.
How to do it?

Categories