add class to element returning unexpected results - javascript

<div id="er_msg" style="width:200px;" align="center"></div>
I am adding a class to the above div with JavaScript:
function validateForm()
{
var x=document.forms["form1"]["email_id"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
document.getElementById("er_msg").innerHTML="Pls enter a valid E-Mail Address ";
document.getElementById("er_msg").className="alert alert-error";
}else{
document.getElementById("er_msg").innerHTML="Thank you!";
document.getElementById("er_msg").className="alert alert-success";
saveAppdata();
}
}
Ideally I should get a red colored "Pls enter a valid E-Mail Address" and a green "Thank you!", whereas in this case both messages appear in red. The classes are predefined by Twitter Bootstrap.

I tested your javascript function using Twitter bootstraps css classes and it works without a problem.
Here is my jsfiddle code: http://jsfiddle.net/yqRCX/
Here are the css classes:
.alert {
padding: 8px 35px 8px 14px;
margin-bottom: 20px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
background-color: #fcf8e3;
border: 1px solid #fbeed5;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.alert, .alert h4 {
color: #c09853;
}
.alert h4 {
margin: 0;
}
.alert .close {
position: relative;
top: -2px;
right: -21px;
line-height: 20px;
}
.alert-success {
color: #468847;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success h4 {
color: #468847;
}
.alert-danger, .alert-error {
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}
.alert-danger h4, .alert-error h4 {
color: #b94a48;
}
So the answer is.. I don't see any problem with the code you have supplied. Your add class works.
If you have other problems please supply more information like what e-mail values you are trying and such.

Related

How make a textarea with tags in react that have clickable dropdown

Id like to make a component in react that allows me to have a textarea with tags that can be inserted when clicked from a dropdown. Id also like this textarea to be able to mix text aswell. I have currently been trying to use tagify with react but I cant seem to figure out a way to the tagify's function that adds the tag to be accessed by the onClick that is connected to the dropdown.
Any ideas?
I believe you can get your answer in this URL of other question asked on StackOverflow https://stackoverflow.com/a/38119725/15405352
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');
// yeah, browser sniffing sucks, but there are browser-specific quirks to handle that are not a matter of feature detection
var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);
function applyHighlights(text) {
text = text
.replace(/\n$/g, '\n\n')
.replace(/[A-Z].*?\b/g, '<mark>$&</mark>');
if (isIE) {
// IE wraps whitespace differently in a div vs textarea, this fixes it
text = text.replace(/ /g, ' <wbr>');
}
return text;
}
function handleInput() {
var text = $textarea.val();
var highlightedText = applyHighlights(text);
$highlights.html(highlightedText);
}
function handleScroll() {
var scrollTop = $textarea.scrollTop();
$backdrop.scrollTop(scrollTop);
var scrollLeft = $textarea.scrollLeft();
$backdrop.scrollLeft(scrollLeft);
}
function fixIOS() {
// iOS adds 3px of (unremovable) padding to the left and right of a textarea, so adjust highlights div to match
$highlights.css({
'padding-left': '+=3px',
'padding-right': '+=3px'
});
}
function bindEvents() {
$textarea.on({
'input': handleInput,
'scroll': handleScroll
});
$toggle.on('click', function() {
$container.toggleClass('perspective');
});
}
if (isIOS) {
fixIOS();
}
bindEvents();
handleInput();
#import url(https://fonts.googleapis.com/css?family=Open+Sans);
*, *::before, *::after {
box-sizing: border-box;
}
body {
margin: 30px;
background-color: #f0f0f0;
}
.container, .backdrop, textarea {
width: 460px;
height: 180px;
}
.highlights, textarea {
padding: 10px;
font: 20px/28px 'Open Sans', sans-serif;
letter-spacing: 1px;
}
.container {
display: block;
margin: 0 auto;
transform: translateZ(0);
-webkit-text-size-adjust: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid #685972;
background-color: #fff;
overflow: auto;
pointer-events: none;
transition: transform 1s;
}
.highlights {
white-space: pre-wrap;
word-wrap: break-word;
color: transparent;
}
textarea {
display: block;
position: absolute;
z-index: 2;
margin: 0;
border: 2px solid #74637f;
border-radius: 0;
color: #444;
background-color: transparent;
overflow: auto;
resize: none;
transition: transform 1s;
}
mark {
border-radius: 3px;
color: transparent;
background-color: #b1d5e5;
}
button {
display: block;
width: 300px;
margin: 30px auto 0;
padding: 10px;
border: none;
border-radius: 6px;
color: #fff;
background-color: #74637f;
font: 18px 'Opens Sans', sans-serif;
letter-spacing: 1px;
appearance: none;
cursor: pointer;
}
.perspective .backdrop {
transform:
perspective(1500px)
translateX(-125px)
rotateY(45deg)
scale(.9);
}
.perspective textarea {
transform:
perspective(1500px)
translateX(155px)
rotateY(45deg)
scale(1.1);
}
textarea:focus, button:focus {
outline: none;
box-shadow: 0 0 0 2px #c6aada;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="backdrop">
<div class="highlights"></div>
</div>
<textarea>This demo shows how to highlight bits of text within a textarea. Alright, that's a lie. You can't actually render markup inside a textarea. However, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there. JavaScript takes care of syncing the content and scroll position from the textarea to the div, so everything lines up nicely. Hit the toggle button to peek behind the curtain. And feel free to edit this text. All capitalized words will be highlighted.</textarea>
</div>
<button>Toggle Perspective</button>
Reference- https://codepen.io/lonekorean/pen/gaLEMR for example

How do you change a CSS property in a javascript file?

I am wondering how to change the border of lock:before to solid transparent when the correct password is entered.
My JavaScript is like this, I need a lock before value to change to solid transparent when the IF is triggered
function lock(){
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
alert("Lock opened");
} else {
alert("Wrong password");
}
}
My CSS is like this, lock before needs to be changed to solid transparent by a javascript function.
body {
position: absolute;
color: #00ff80;
background: green;
top: 100px;
left: 200px;
}
#lock {
font-size: 8px;
position: relative;
width: 18em;
height: 13em;
border-radius: 2em;
top: 10em;
box-sizing: border-box;
border: 3.5em solid red;
border-right-width: 7.5em;
border-left-width: 7.5em;
margin: 0 0 6rem 0;
}
#lock:before {
content: "";
box-sizing: border-box;
position: absolute;
border: 2.5em solid red;
width: 14em;
height: 12em;
left: 50%;
margin-left: -7em;
top: -12em;
border-top-left-radius: 7em;
border-top-right-radius: 7em;
}
#lock:after {
content: "";
box-sizing: border-box;
position: absolute;
border: 1em solid red;
width: 5em;
height: 8em;
border-radius: 2.5em;
left: 50%;
top: -1em;
margin-left: -2.5em;
}
#button {
background: transparent;
}
My HTML is like this, all it does is make a button and some text.
<!DOCTYPE html>
<html>
<head>
<title>The lock</title>
</head>
<body>
<h1>Unlock the lock</h1>
<button id=button onclick="lock()"><div id=lock></div></button>
</body>
</html>
Try something like this..
var str = '1em solid transparent';
document.styleSheets[0].addRule('#lock:before','border: "'+str+'";');
the style of a pseudo-element can be changed by using a new class name. For example, add the class name unlocked to the #lock element once the entered password is valid.
You can add the following style for the new class:
#lock.unlocked::before {
border: 1em solid transparent;
/* Your style for unlocked goes here */
}
And your script with the new instruction which add the class .unlocked.
function lock() {
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
alert("Lock opened");
document.getElementById("lock").classList.add("unlocked"); /* NEW */
} else {
alert("Wrong password");
}
}
Add and remove a class to and from the button. Pseudo elements can't be targeting directly from JavaScript so you have to use CSS to change the styling.
// Select the button
const button = document.querySelector('button');
function lock(){
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
// Add the class.
button.classList.add('unlocked');
// If it already has the class..
} else if (button.classList.contains('unlocked')) {
//.. then remove it.
button.classList.remove('unlocked');
}
}
And in your CSS add the class with the styling you need.
#lock.unlocked::before {
border: 2.5em solid transparent;
}

Wondering why my javascript file isn't loading when I run phonegap?

Let me know if I have to post this a different way, but I uploaded the three files I am working with. I am pretty new to jQuery and javascript but in my class I am supposed to be able to get this combination of files running and what is supposed to be happening when I run this HTML file is that when I hit "Submit" on the bottom of the form without entering anything into the text areas, it should return an error message and a little exclamation mark.
Currently, it isn't returning anything at all. The .css file loads fine and changes my form to look like what it is supposed to, but not the .js file. I am wondering if it has something to do with the script tags in the head section of the html file?
For context, I did write most of this myself from the book instructions but apparently the school provided the completed code in separate files which was formatted much cleaner than mine, so I just replaced mine with what you see here. The main section that wasn't clarified on either in the book or by my professor (good luck, he doesn't answer emails) is the information to load Jquery/javascript files in the header section. I am using phoneGap to emulate this web page.
var errors = {};
function displayErrors() {
// initialise variables
var haveErrors = false;
// remove the invalid class for all inputs
$(":input.invalid").removeClass("invalid");
// iterate through the fields specified in the errors array
for (var fieldName in errors) {
haveErrors = true;
$("input[name='" + fieldName + "']").addClass("invalid");
} // for
// if we have errors, then add a message to the errors div
$("#errors")
.html(haveErrors ? "Errors were found." : "")
.css("display", haveErrors ? "block" : "none");
} // displayErrors
function displayFieldErrors(field) {
var messages = errors[field.name];
if (messages && (messages.length > 0)) {
// find an existing error detail section for the field
var errorDetail = $("#errordetail_" + field.id).get(0);
// if it doesn't exist, then create it
if (! errorDetail) {
$(field).before("<ul class='errors-inline' id='errordetail_" + field.id + "'></ul>");
errorDetail = $("#errordetail_" + field.id).get(0);
} // if
// add the various error messages to the div
for (var ii = 0; ii < messages.length; ii++) {
$(errorDetail).html('').append("<li>" + messages[ii] + "</li>");
} // for
} // if
} // displayFieldErrors
$(document).ready(function() {
$(":input").focus(function(evt) {
displayFieldErrors(this);
}).blur(function(evt) {
$("#errordetail_" + this.id).remove();
});
$("#taskentry").validate({
submitHandler: function(form) {
// TO BE COMPLETED IN THE NEXT CHAPTER
},
showErrors: function(errorMap, errorList) {
// initialise an empty errors map
errors = {};
// iterate through the jQuery validation error map, and convert to
// something we can use
for (var elementName in errorMap) {
if (! errors[elementName]) {
errors[elementName] = [];
} // if
errors[elementName].push(errorMap[elementName]);
} // for
// now display the errors
displayErrors();
}
});
});
body {
margin: 0px;
min-height: 480px;
font-family: Arial;
}
form ul {
margin: 0px;
padding: 6px;
list-style-type: none;
}
form ul li {
margin: 0 0 4px 0;
-webkit-border-radius: 4px;
border: 1px solid #666666;
padding: 4px;
}
form ul li.naked {
-webkit-border-radius: 0px;
border: 0;
padding: 0;
}
input, textarea {
-webkit-appearance: none;
border: 0;
width: 99%;
}
input.invalid, textarea.invalid {
background: url(exclamation.png) no-repeat 2px 2px;
padding-left: 22px;
}
#errors {
margin: 8px 6px 2px 6px;
padding: 6px 14px;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #cc0000), color-stop(0.7, #770022));
-webkit-border-radius: 4px;
color: white;
display: none;
}
ul.errors-inline li {
border: 0px;
color: red;
padding: 0px;
}
input[type=submit] {
border: 1px solid white;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #F8F8F8), color-stop(1.0, #AAAAAA));
-webkit-border-radius: 6px;
-webkit-box-shadow: 0 0 4px #333333;
width: 100%;
padding: 6px;
}
h1.simple {
font-size: 0.9em;
padding: 8px 4px 4px 8px;
background: #333333;
color: #AAAAAA;
border-bottom: 2px solid #AAAAAA;
margin: 0 0 4px 0;
}
h1.fancy {
background: -webkit-gradient(linear, left top, left bottom, color-stop(0.0, #666666), color-stop(0.5, #3A3A3A), color-stop(0.5, #222222), color-stop(1.0, #000000));
-webkit-box-shadow: 0 2px 1px #AAAAAA;
-webkit-border-bottom-left-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
font-size: 1.1em;
color: white;
padding: 10px 8px;
margin: 0 6px 6px 6px;
text-align: center;
}
<html>
<head>
<title>Simple Mobile Web Page</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<link rel="stylesheet" media="screen" href="todolist.css" />
<script type="text/javascript" src="../../js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../js/jquery.validate.js"></script>
<script type="text/javascript" src="todolist.js"></script>
</head>
<body>
<h1 class="fancy">Christopher Hughes To Do List</h1>
Hello World!
<p>
This is just the beginning!
</p>
<span class="highlight">
More to come!
</span>
<h1 class="fancy">Create Task</h1>
<div id="errors"></div>
<form id="taskentry">
<ul>
<li><input type="text" name="task[name]" id="taskname" placeholder="Task Name"/></li>
<li>
<textarea name="task[description]" id="taskdesc" placeholder="Description" rows="5"></textarea>
</li>
<li><input type="text" name="task[due]" id="taskdue" placeholder="Task Due" /></li>
<li class="naked"><input type="submit" name="Save" /></li>
</ul>
</form>
</body>
</html>

Mapbox + jsFiddle + Wordpress

I apologize in advance for my very limited knowledge of coding. I've been trying to add a custom search bar linked to Mapbox on my Wordpress site without any luck. I created, or actually I edited a jsFiddle that I found. Where I'm having trouble is adding the Javascript from jsFiddle to Wordpress...
Here's the working jsFiddle: https://jsfiddle.net/erinlink/4q9brvkt/16/
L.mapbox.accessToken = 'pk.eyJ1IjoiZXJpbmxpbmsiLCJhIjoiWnpiWXQ5RSJ9.hy5rpmPf-gpFRaNG7GHfAA';
var geocoder = L.mapbox.geocoder('mapbox.places'),
map = null;
var map = L.mapbox.map('mapbox', 'erinlink.bee96628').setView([30.267153, -97.74306079999997], 12);
var featureLayer = L.mapbox.featureLayer('erinlink.bee96628')
.addTo(map);
/*
var featureLayer = L.mapbox.featureLayer()
.addTo(map);
featureLayer.loadID('your_id');
*/
// both versions to add the featurelayer work
function showMap(err, data) {
// The geocoder can return an area, like a city, or a
// point, like an address. Here we handle both cases,
// by fitting the map bounds to an area or zooming to a point.
if (!map) {
map = L.mapbox.map('mapbox', 'erinlink.bee96628');
}
if (data.lbounds) {
map.fitBounds(data.lbounds);
} else if (data.latlng) {
map.setView([data.latlng[0], data.latlng[1]], 12);
}
}
function geocodeThis() {
var text = document.getElementById('searchMap').value;
if (text.length >= 5) {
geocoder.query(text, showMap);
}
}
body {
margin: 0;
padding: 0;
}
#mapbox {
width: 100%;
height: 100%;
border: 0px solid transparent;
}
#searchMap {
z-index: 10000 !important;
position: relative;
float: right;
text-overflow: ellipsis;
padding: 2px 0px 2px 6px;
background-color: #fff;
color: gray;
font-size: 12pt;
font-family: Trebuchet MS;
height: 24px;
width: 200px;
border: 0px solid transparent;
border-radius: 4px 4px 4px 4px;
margin: 0px 120px 10px 10px;
}
.mapbox_header {
color: white;
text-align: right;
font-size: 10pt;
font-family: Trebuchet MS;
font-style: italic;
font-weight: 100;
margin: 10px 120px 10px 0;
}
<link href="https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js"></script>
<div style="margin-top:1px; padding: 4px 40px 0px 0px; background: #77bc1f; width:100%; height:10%;">
<div>
<ul>
<input type='text' oninput='geocodeThis()' id='searchMap' placeholder='Enter address or zip'>
<br>
<br>
<p class="mapbox_header">Looking for a particular flavor or bottle size in your area? Contact us for more info.</p>
</ul>
</div>
</div>
<div>
<div id='mapbox' style="height:400px; width:100%;"></div>
</div>
Here's the page I've been trying to get it working on (the current
map on this page is not linked to the search bar):
http://yellowbirdsauce.com/locations/
Thanks in advance for any help!!

How to check if a table is visible or not with javascript?

first of all i'll explain the situation:
I can ONLY write in the body of an html, this is because of some limitations.
I need to replace the website (a profile) for a new one.
The issue is: the menu should show or hide sections on click... and isn't.
I don't really know much of javascript, just a bit of python and because of that i'm getting some issues with the code, but i won't learn javascript much either since this will probably be just a once in a lifetime for me.
I don't want to add jQuery code.
So... i tried this code in http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_background, (copy and pasty so you can also check) but it doesnt works as expected, the function for the menu isn't working.
<!DOCTYPE html><html><head></head><body><script>
function comandos()
{
var visibilidaddecomandos = document.getElementById("comandos").style.display;
if (visibilidaddecomandos == "hidden")
{
document.getElementById("comandos").style.visibility = "visible";
}
else if (visibilidaddecomandos == "visible")
{
document.getElementById("comandos").style.visibility = "hidden";
}
return false;
}
document.write('<style> #navcontainer { margin: 10px 0 0 30px; padding: 0; height: 20px; } #navcontainer ul { border: 0; margin: 0; padding: 0; list-style-type: none; text-align: center; } #navcontainer ul li { display: block; float: left; text-align: center; padding: 0; margin: 0; } #navcontainer ul li a { background: #fff; width: 78px; height: 18px; border-top: 1px solid #ddd; border-left: 1px solid #ddd; border-bottom: 1px solid #ddd; border-right: 1px solid #ddd; padding: 0; margin: 0 0 5px 0; color: #666; text-decoration: none; display: block; text-align: center; font: normal 10px/18px verdana; } #navcontainer ul li a:hover { color: #6659A7; background: #eeeeee; } #navcontainer a:active { background: #c60; color: #fff; } #navcontainer li#active a { background: #c60; border: 1px solid #c60; color: #fff; } </style> <div id="navcontainer"> <ul> <li><span>Comandos</span></li><li><span>Estadisticas</span></li><li><span>Juegos</span></li><li><span>Sobre mi</span></li><li><span>Saelyth</span></li></ul> </div>');
document.write('<br><table id="global" style="background-color:#ffffff; width:460px; height:600px"><tr><td style="vertical-align:top"><table id="comandos" border="2" style="background-color:#000000; float:center"><tr><td><p style="color:red">Testing the ID table "comandos"</p></td></tr></table></td></tr></table>');
document.body.style.background="#66ffff url('http://images.wikia.com/xenosaga/images/8/86/KOSMOSWikiBG.jpg') no-repeat left top"
document.title = "¡My not working menu!";
window.stop();
</script>
</body></html>
Although tables are not best practice..for multiple reasons.. one being that the entire table has to load before your data is shown.
Divs are your best friend.
Anyways, here is the fix I believe you are looking for.
function comandos()
{
var visibilidaddecomandos = document.getElementById("comandos").style.visibility;
if (visibilidaddecomandos == "hidden")
{
document.getElementById("comandos").style.visibility = "visible";
}
else if (visibilidaddecomandos == "visible")
{
document.getElementById("comandos").style.visibility = "hidden";
}
return false;
}
Also you have to add a default visibility to your table in order for it to work.
<table id="comandos" border="2" style="visibility:visible;background-color:#000000; float:center">
var visibilidaddecomandos = document.getElementById("comandos");
if (visibilidaddecomandos.style.visibility == 'hidden')
{
visibilidaddecomandos.style.visibility = "visible";
}
else if (visibilidaddecomandos.style.visibility == "visible")
{
visibilidaddecomandos.style.visibility = "hidden";
}
This will work....
if (document.getElementById("comandos").style.visibility == "hidden"){document.getElementById("comandos").style.visibility == "visible";}else if (document.getElementById("comandos").style.visibility == "visible")
{document.getElementById("comandos").style.visibility == "hidden";}
Hope this will help.

Categories