Trouble showing div ID - javascript

I have a basic Decision Tree. It has an Answer field and a Message field. I am having trouble displaying JavaScript inside the "Message" area using its ID.
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href="~/Content/styles.css" type="text/css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script src="~/Scripts/tree.js"></script>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<title>Test Tree</title>
<style>
a {
color: #ffffff;
}
a:hover {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
body {
font: 'Gotham Book', Gotham-Book, Arial, sans-serif;
background-color: #f2f2f2;
}
h1 {
margin: 40px auto 5px auto;
text-align: center;
}
.dc-tree {
font: 16px 'Roboto',Verdana, sans-serif;
position: relative;
text-align: center;
background-color: #f2f2f2;
height: 50%;
overflow: hidden;
}
.dc-tree * {
box-sizing: border-box;
}
.dctree-card {
text-align: center;
padding: 0px;
position: absolute;
margin: 0 auto;
background-color: #f2f2f2;
display: none;
}
.dctree-message {
padding: 10px;
margin-bottom: 20px;
font-size: 1.5em;
}
[class^="dctree-answer"] {
padding: 20px;
/*added height 10vh to auto-align boxes*/
height: 10vh;
text-align: center justify;
margin: 15px 120px;
box-shadow: 3px 3px 5px 2px #BDBDBD;
/*position: fixed;*/
/*text-shadow: 1px 1px 2px black;*/
}
.darkBlue {
background-color: #003E69;
color: white;
}
.softBlack {
background-color: #333333;
color: white;
}
.lightGrey {
background-color: #808080;
color: white;
}
.teal {
background-color: #38939b;
color: white;
}
.green {
background-color: #5E9732;
color: white;
}
.orange {
background-color: #F47B20;
color: white;
}
.footer {
font: 'Gotham Book', Gotham-Book, Arial, sans-serif;
position: fixed;
left: 0;
bottom: 80px;
width: 100%;
background-color: #f2f2f2;
color: black;
text-align: center;
font-size: 16px;
padding: 5px;
/*text-decoration: underline;*/
}
</style>
<script>
(function ($) {
var settings;
var currentCard;
var prevCard = [];
// Plugin definition.
$.fn.decisionTree = function (options) {
var elem = $(this);
settings = $.extend({}, $.fn.decisionTree.defaults, options);
elem.addClass(settings.containerClass);
renderRecursive(settings.data, elem, "dctree-first");
$('.dctree-prev').on('click', function () {
showCard(prevCard.pop(), true);
});
currentCard = $('#dctree-first');
currentCard.show();
};
$.fn.decisionTree.defaults = {
data: null,
animationSpeed: "fast",
animation: "slide-left",
containerClass: "dc-tree",
cardClass: "dctree-card",
messageClass: "dctree-message"
};
function renderRecursive(data, elem, id) {
var container = $('<div></div>')
.addClass(settings.cardClass)
.addClass('col-xs-12');
var message = $('<div></div>').addClass(settings.messageClass).append(data.message);
message.append('');
message.append('<div id="heading"></div>');
container.append(message);
if (id != null) {
container.attr('id', id)
}
if (typeof data.decisions != "undefined") {
var decisions = $('<div></div>').addClass('dctree-decisions');
for (var i = 0; data.decisions.length > i; i++) {
var decision = data.decisions[i];
var genId = guid();
var grid = $('<div></div>').addClass('col-md-6');
var answer = $('<div></div>')
.addClass("dctree-answer-" + i)
.append(decision.answer, '')
.on('click', function () {
getNextCard(this);
})
.attr('data-dctree-targetid', genId);
if (typeof decision.class != "undefined") {
answer.addClass(decision.class);
}
grid.append(answer);
decisions.append(grid);
renderRecursive(decision, elem, genId);
}
container.append(decisions);
}
if (id != 'dctree-first') {
var controls = $('<div></div>').addClass('dctree-controls col-md-12');
controls.append($('< Back'));
container.append(controls);
}
elem.append(container);
$('.dctree-message').click(function () { console.log("Hi"); })
}
function getNextCard(elem) {
var e = $(elem);
currentCard = e.parents('.' + settings.cardClass)[0];
prevCard.push(currentCard.id);
var nextCard = e.attr('data-dctree-targetid');
showCard(nextCard);
}
function showCard(id, backward) {
var nextCard = $("#" + id);
if (settings.animation == 'slide') {
$(currentCard).slideUp(settings.animationSpeed, function () {
nextCard.slideDown(settings.animationSpeed);
});
} else if (settings.animation == 'fade') {
$(currentCard).fadeOut(settings.animationSpeed, function () {
nextCard.fadeIn(settings.animationSpeed);
});
} else if (settings.animation == 'slide-left') {
var left = { left: "-100%" };
var card = $(currentCard);
if (backward) {
left = { left: "100%" };
}
card.animate(left, settings.animationSpeed, function () {
card.hide();
});
if (nextCard.css('left') == "-100%" || nextCard.css('left') == "100%") {
left.left = 0;
nextCard.show().animate(left, settings.animationSpeed);
} else {
nextCard.fadeIn(settings.animationSpeed);
}
}
currentCard = nextCard;
}
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// End of closure.
})(jQuery);
</script>
<script>
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
if (a.indexOf('html') > -1) { //Check of html String in URL.
url = url.substring(0, newURL.lastIndexOf("."));
}
//Gets current date and subtracts 7 days. This is to check whether the decision is 7 days prior to today's date.
var d = new Date();
d.setDate(d.getDate() - 7);
document.getElementById('heading').innerHTML = "I bought it " + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear() + "?"; </script>
<div class="jquery-script-center">
<div class="jquery-script-clear"></div>
</div>
<!--</div>-->
<h1>Dolls</h1>
<div class="main"></div>
<script type="text/javascript">
var data = {
message: "<div style='color:black;'>Are you buying a doll?</div>",
decisions: [{
answer: "ACH",
class: "green",
message: "<div id='heading'></div>",
decisions: [{
answer: "I love it",
class: "orange",
message: "It's my favorite"
},
{
answer: "I don't like it",
class: "green",
message: "It's not my favorite"
},
]
},
]
},
]
},
]
};
$(document).ready(function () {
$('.main').decisionTree({
data: data
});
});
My intent is, for the message that has id=heading, I'd like it to display the JavaScript for the date. However, when I try to launch it in my browser, it refuses to show. Can someone help me with I may be doing wrong? Thank you!

I think your heading div doesn't exist when your script runs initially...all the script is loaded prior to $(document).ready and that is where the "heading" div is added. As a test, I put the date/time code in a function and called it after the
$('.main').decisionTree statement, and I think it worked as expected.
function lateBinder(){
var d = new Date();
d.setDate(d.getDate() - 7);
document.getElementById('heading').innerHTML = "I bought it " + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear() + "?";
}
$(document).ready(function () {
$('.main').decisionTree({
data: data
});
lateBinder();
});

It seems you have too many closing brackets in your variable "data" object.

Related

How can I create a dynamic list of Input field which create another input field when you write and delete it when the input is empty?

I'm new to jQuery and in my current project I need to create a list of inputs with following conditions:
When I write something in the first input field another input fields spawns
When I delete the chars and the input field is empty, it will be deleted
In the end all the values will be combined into one string
If possible the list should be in an array (optional)
I'm limited because my knowledge of jQuery isn't good. I managed to create the first condition but I don't know if my solution is any good.
http://jsfiddle.net/kubydpvr/5/
$(document).ready(() => {
let count = 0;
let arr = [createInput(0)];
$(".Fields").append(arr);
function addListField() {
$("#id_" + count).one("input", addListField);
$("#id_" + count).attr({
type: "text"
});
arr.push(createInput(count + 1, "hidden"));
$("#id_" + count).after(createInput(count + 1, "hidden"));
count++;
}
function createInput(id, type = "text") {
return (
"<input type=" + type + ' value = "" id = id_' + id + " ></input>"
);
}
addListField();
});
body {
font-size: 17px;
font-family: "Courier New", Courier, monospace;
background: whitesmoke;
line-height: 1.5em;
}
header {
background: rgb(1, 60, 14);
color: whitesmoke;
padding: 20px;
text-align: center;
border-bottom: 4px rgb(26, 0, 62) solid;
margin-bottom: 10px;
}
.container {
margin: auto;
padding: 10px;
width: 200px;
}
.Fields {
display: flex;
flex-direction: column;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<header>
<h1>I Learn jQuery.</h1>
<div class="container">
<div class="Fields"></div>
</div>
I think this is what your after
$(document).ready(() => {
let count = 0;
let arr = [createInput(0)];
$(".Fields").append(arr);
function addListField() {
$("#id_" + count).one("input", addListField);
$("#id_" + count).on("change", function() {
let item = parseInt($(this).attr("id").split("_")[1]);
if (!$(this).val().length) {
arr.splice(item, 1)
$(this).remove();
}
})
$("#id_" + count).attr({
type: "text"
});
arr.push(createInput(count + 1, "hidden"));
$("#id_" + count).after(createInput(count + 1, "hidden"));
count++;
}
$("#output").on("click", function() {
let vals = [];
$('[id^=id_]').each(function() {
if ($(this).val() !== "") {
vals.push($(this).val())
}
//vals += $(this).val()
})
console.log(vals)
console.log(arr)
})
function createInput(id, type = "text") {
return (
"<input type=" + type + ' value = "" id = id_' + id + " ></input>"
);
}
addListField();
});
body {
font-size: 17px;
font-family: "Courier New", Courier, monospace;
background: whitesmoke;
line-height: 1.5em;
}
header {
background: rgb(1, 60, 14);
color: whitesmoke;
padding: 20px;
text-align: center;
border-bottom: 4px rgb(26, 0, 62) solid;
margin-bottom: 10px;
}
.container {
margin: auto;
padding: 10px;
width: 200px;
}
.Fields {
display: flex;
flex-direction: column;
}
<!DOCTYPE html>
<html>
<head>
<title>Learn jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<header>
<h1>I Learn jQuery.</h1>
<div class="container">
<div class="Fields"></div>
</div>
<button id="output">
Output
</button>
</header>
</body>
</html>
I hope this helps

Change the color of new added element by jQuery

this is my code:
jQuery(document).on('change', 'input[type=color]', function(picker) {
var color_chng = jQuery(this).closest('.input-group').attr('id');
jQuery('.card-txt[id=p' + color_chng + ']').css('color', picker.currentTarget.value);
});
jQuery(document).ready(function() {
var img_url = jQuery("#pro-image").attr('src');
jQuery(".edit-image").css('background', 'url(' + img_url + ')');
jQuery(".hide-img").attr('src', img_url);
jQuery(".edit-btn").find(".elementor-button-link").click(function() {
jQuery(".edit-box").show();
});
//input keyup
jQuery(document).on('keydown, keyup', '.input-group input[type="text"]', function() {
var texInputValue = jQuery(this).val();
var input_id = jQuery(this).parent().attr('id');
jQuery('.edit-image span[id=p' + input_id + ']').html(texInputValue);
});
// Draggable
(function(jQuery) {
jQuery.fn.drags = function(opt) {
opt = jQuery.extend({
handle: "",
cursor: "move"
}, opt);
if (opt.handle === "") {
var jQueryel = this;
} else {
var jQueryel = this.find(opt.handle);
}
return jQueryel.css('cursor', opt.cursor).on("mousedown", function(e) {
if (opt.handle === "") {
var jQuerydrag = jQuery(this).addClass('draggable');
} else {
var jQuerydrag = jQuery(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = jQuerydrag.css('z-index'),
drg_h = jQuerydrag.outerHeight(),
drg_w = jQuerydrag.outerWidth(),
pos_y = jQuerydrag.offset().top + drg_h - e.pageY,
pos_x = jQuerydrag.offset().left + drg_w - e.pageX;
jQuerydrag.css('z-index', 1000).parents().on("mousemove", function(e) {
jQuery('.draggable').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup", function() {
jQuery(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup", function() {
if (opt.handle === "") {
jQuery(this).removeClass('draggable');
} else {
jQuery(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
jQuery('.draggble').drags();
// Duplicate
var buttonAdd = jQuery(".addtxt");
var buttonRemove = jQuery(".removetxt");
var className = ".input-group";
var className2 = ".card-txt";
var count = 0;
var field = "";
var field2 = "";
var maxFields = 5;
function totalFields() {
return jQuery(className).length;
}
function addNewField() {
count = totalFields() + 1;
field2 = jQuery("#ptxtgrp1").clone();
field2.attr("id", "ptxtgrp" + count);
field2.html("");
field2.attr('style', '');
jQuery(field2).drags();
field = jQuery("#txtgrp1").clone();
field.attr("id", "txtgrp" + count);
field.find("input").val("");
jQuery(className + ":last").after(jQuery(field));
jQuery(className2 + ":last").after(jQuery(field2));
count++;
}
function removeLastField() {
if (totalFields() > 1) {
jQuery(className + ":last").remove();
jQuery(className2 + ":last").remove();
}
}
function enableButtonRemove() {
if (totalFields() === 2) {
buttonRemove.removeAttr("disabled");
buttonRemove.addClass("shadow-sm");
}
}
function disableButtonRemove() {
if (totalFields() === 1) {
buttonRemove.attr("disabled", "disabled");
buttonRemove.removeClass("shadow-sm");
}
}
function disableButtonAdd() {
if (totalFields() === maxFields) {
buttonAdd.attr("disabled", "disabled");
buttonAdd.removeClass("shadow-sm");
}
}
function enableButtonAdd() {
if (totalFields() === (maxFields - 1)) {
buttonAdd.removeAttr("disabled");
buttonAdd.addClass("shadow-sm");
}
}
buttonAdd.on("click", function() {
addNewField();
enableButtonRemove();
disableButtonAdd();
});
buttonRemove.on("click", function() {
removeLastField();
disableButtonRemove();
enableButtonAdd();
});
// Hide Show Texts
jQuery(document).on('click', '.show', function() {
var txt_id = jQuery(this).parent().attr('id');
jQuery(".card-txt[id=p" + txt_id + "]").toggle();
jQuery(this).toggleClass("hide");
});
// Font Size Change
jQuery(".input-group").each(function() {
jQuery(document).on('click', '.font-up', function() {
var ftxt_id = jQuery(this).parent().attr('id');
var size = jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size");
size = parseInt(size, 10);
if ((size + 2) <= 70) {
jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size", "+=2");
}
});
jQuery(document).on('click', '.font-down', function() {
var ftxt_id = jQuery(this).parent().attr('id');
var size = jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size");
size = parseInt(size, 10);
if ((size - 2) >= 12) {
jQuery('.card-txt[id=p' + ftxt_id + ']').css("font-size", "-=2");
}
});
});
});
.edit-box {
width: 600px;height:300px;
margin: 0 auto;
display: block;
border: 2px solid #dddddd;
border-radius: 10px;
background: #eee;
}
body {
height: 3000px;
}
/***************************/
.edit-image {
background-size: cover;
width: max-content;
display: block;
background: red;
margin: 40px auto;
position: relative;width:200px;height:200px;backgrounf:red;
}
.edit-contents {
width: 80%;
display: block;
margin: 20px auto;
background: #fff;
padding: 20px;
}
.card-txt {
position: absolute;
top: 50%;
left: 50%;
}
.show,
.font-up,
.font-down {
background: green;
width: 20px;
height: 20px;
display: inline-block;
color: #fff;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
}
.addtxt,
.removetxt {
margin: 10px;
display: inline;
}
.show.hide {
background: red;
}
[type='color'] {
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
padding: 0;
width: 15px;
height: 15px;
border: none;
}
[type='color']::-webkit-color-swatch-wrapper {
padding: 0;
}
[type='color']::-webkit-color-swatch {
border: none;
}
.color-picker {
padding: 10px 15px;
border-radius: 10px;
border: 1px solid #ccc;
background-color: #f8f9f9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="edit-box">
<div class="edit-image">
<img class="hide-img" src="" style="visibility: hidden;" />
<span class="card-txt draggble" id="ptxtgrp1"></span>
</div>
<div class="edit-contents">
<button type="button" class="addtxt">Add</button>
<button type="button" class="removetxt">remove</button>
<div class="input-group" id="txtgrp1">
<input class="inptxt" type="text">
<i class="show"></i>
<i class="font-up">+</i>
<i class="font-down">-</i>
<span class="color-picker">
<label for="colorPicker">
<input type="color" value="#1DB8CE" class="colorPicker" >
</label>
</span>
</div>
</div>
</div>
as you can see I need to add new texts dynamically to the "edit-image" box and I need users to change the size and color of added texts.
the first input box that already exists in DOM change color works fine
but when I add another input box by jquery codes the change color function doesn't work for it
I would be thankful if you can help me to find out the reason and resolve the issue

How can I send form_id to javascript function as a parameter?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Başlıksız Belge</title>
<style>
body
{
font-family: Open sans, Helvetica;
background: #111;
color: white;
font-size: 16px;
}
h1
{
font-weight: lighter;
}
small
{
color: firebrick;
}
div.checkbox_select
{
width: 200px;
}
.checkbox_select_anchor
{
display: block;
background: firebrick;
color: white;
cursor: pointer;
padding: 10px 5px 5px;
position: relative;
}
.checkbox_select_anchor:after
{
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid darkred;
content: "";
position: absolute;
right: 10px;
top: 15px;
}
.expanded .checkbox_select_anchor:after
{
border-top: 0;
border-bottom: 10px solid firebrick;
}
.checkbox_select_anchor:hover
{
background: #FF3030 !important;
}
.expanded .checkbox_select_anchor
{
background: #7C1818;
}
div.checkbox_select .select_input
{
width: 100%;
cursor: pointer;
}
.checkbox_select_dropdown
{
display: none;
background: whitesmoke;
}
.checkbox_select_dropdown.show
{
display: block;
}
.checkbox_select_dropdown ul
{
max-height: 150px;
overflow-y: scroll;
overflow-x: hidden;
padding: 0;
margin: 0;
border: 1px solid #999;
border-top: 0;
border-bottom: 0;
}
.checkbox_select_dropdown ul li
{
list-style: none;
position: relative;
color: #666;
}
.checkbox_select_dropdown ul li label
{
position: relative;
padding: 10px 5px 5px 40px;
display: block;
cursor: pointer;
}
.checkbox_select_dropdown ul li label:hover
{
background: #cbcbcb;
color: white;
}
.checkbox_select_dropdown ul li input:checked + label
{
background: #bbb;
color: white;
text-shadow: 0px 1px 1px rgba(150, 150, 150, 1);
}
.checkbox_select_dropdown ul li input
{
position: absolute;
left:0;
z-index:1;
display: inline-block;
height: 100%;
width: 30px;
}
.checkbox_select_search
{
width: 200px;
padding: 10px 5px 5px;
border: 1px solid #999;
border-top: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.checkbox_select_submit
{
background: #00A600;
color: white;
padding: 10px 5px 5px;
border: 0;
width: 100%;
font-size: 14px;
cursor: pointer;
}
.hide
{
display: none;
}
</style>
</head>
<body>
<h1>multiselect</h1>
//here I have an form id and it is used javascript function
<form id="make_checkbox_select">
<select name="Cinsiyet">
<option data-count="(2)" value="Kadin">Kadın </option>
<option data-count="(23)" value="erkek">Erkek </option>
</select>
<input type="submit" />
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function()
{
var mySelectCheckbox = new checkbox_select(
{
selector : "#make_checkbox_select",
selected_translation : "seçildi",
all_translation : "Tamamı Seçildi",
not_found : "Bulunamadı",
// Event during initialization
onApply : function(e)
{
alert("Custom Event: " + e.selected);
}
});
});
// variable_names
// functionNames
// CONSTANT_VARIABLE_NAMES
// $_my_jquery_selected_element
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g, '');
}
}
var checkbox_select = function(params)
{
// Error handling first
// ----------------------------------------------------------------------------------------------------
var error = false;
// If the selector is not given
if(!params.selector) { console.error("selector needs to be defined"); error = true; }
// If the selector is not a string
if(typeof params.selector != "string") { console.error("selector needs to be a string"); error = true; }
// If the element is not a form
if(!$(params.selector).is("form")) { console.error("Element needs to be a form"); error = true; }
// If the element doesn't contain a select
if($(params.selector).find("select").length < 1) { console.error("Element needs to have a select in it"); error = true; }
// If the element doesn't contain option elements
if($(params.selector).find("option").length < 1) { console.error("Select element needs to have an option in it"); error = true; }
// If the select element doesn't have a name attribute
if($(params.selector).find('select').attr('name') == undefined) { console.error("Select element needs to have a name attribute"); error = true; }
// If there was an error at all, dont continue in the code.
if(error)
return false;
// ----------------------------------------------------------------------------------------------------
var that = this,
$_native_form = $(params.selector),
$_native_select = $_native_form.find('select'),
// Variables
selector = params.selector,
select_name = $_native_select.attr('name').charAt(0).toUpperCase() + $_native_select.attr('name').substr(1),
selected_translation = params.selected_translation ? params.selected_translation : "selected",
all_translation = params.all_translation ? params.all_translation : "All " + select_name + "s",
not_found_text = params.not_found ? params.not_found : "No " + select_name + "s found.",
currently_selected = [],
// Create the elements needed for the checkbox select
$_parent_div = $("<div />") .addClass("checkbox_select"),
$_select_anchor = $("<a />") .addClass("checkbox_select_anchor") .text( select_name ),
$_search = $("<input />") .addClass("checkbox_select_search"),
$_submit = $("<input />") .addClass("checkbox_select_submit") .val("Apply") .attr('type','submit') .data("selected", ""),
$_dropdown_div = $("<div />") .addClass("checkbox_select_dropdown"),
$_not_found = $("<span />") .addClass("not_found hide") .text(not_found_text),
$_ul = $("<ul />"),
updateCurrentlySelected = function()
{
var selected = [];
$_ul.find("input:checked").each(
function()
{
selected.push($(this).val());
}
);
currently_selected = selected;
if(selected.length == 0)
{
$_select_anchor.text( select_name )
}
else if(selected.length == 1)
{
$_select_anchor.text( selected[0] + " " + selected_translation );
}
else if(selected.length == $_ul.find("input[type=checkbox]").length)
{
$_select_anchor.text( all_translation );
}
else
{
$_select_anchor.text( selected.length + " " + selected_translation );
}
},
// Template for the li, will be used in a loop.
createItem = function(name, value, count)
{
var uID = 'checkbox_select_' + select_name + "_" + name.replace(" ", "_"),
$_li = $("<li />"),
$_checkbox = $("<input />").attr(
{
'name' : name,
'id' : uID,
'type' : "checkbox",
'value' : value
}
)
.click(
function()
{
updateCurrentlySelected();
}
),
$_label = $("<label />").attr('for', uID),
$_name_span = $("<span />").text(name).prependTo($_label),
$_count_span = $("<span />").text(count).appendTo($_label);
return $_li.append( $_checkbox.after( $_label ) );
},
apply = function()
{
$_dropdown_div.toggleClass("show");
$_parent_div.toggleClass("expanded");
if(!$_parent_div.hasClass("expanded"))
{
// Only do the Apply event if its different
if(currently_selected != $_submit.data("selected"))
{
$_submit.data("selected" , currently_selected);
that.onApply(
{
selected : $_submit.data("selected")
}
);
}
}
};
// Event of this instance
that.onApply = typeof params.onApply == "function" ?
params.onApply :
function(e)
{
//e.selected is accessible
};
that.update = function()
{
$_ul.empty();
$_native_select.find("option").each(
function(i)
{
$_ul.append( createItem( $(this).text(), $(this).val(), $(this).data("count") ) );
}
);
updateCurrentlySelected();
}
that.check = function(checkbox_name, checked)
{
//$_ul.find("input[type=checkbox][name=" + trim(checkbox_name) + "]").attr('checked', checked ? checked : false);
$_ul.find("input[type=checkbox]").each(function()
{
// If this elements name is equal to the one sent in the function
if($(this).attr('name') == checkbox_name)
{
// Apply the checked state to this checkbox
$(this).attr('checked', checked ? checked : false);
// Break out of each loop
return false;
}
});
updateCurrentlySelected();
}
// Build mark up before pushing into page
$_dropdown_div .prepend($_search);
$_dropdown_div .append($_ul);
$_dropdown_div .append($_not_found);
$_dropdown_div .append($_submit);
$_dropdown_div .appendTo($_parent_div);
$_select_anchor .prependTo($_parent_div);
// Iterate through option elements
that.update();
// Events
// Actual dropdown action
$_select_anchor.click(
function()
{
apply();
}
);
// Filters the checkboxes by search on keyup
$_search.keyup(
function()
{
var search = $(this).val().toLowerCase().trim();
if( search.length == 1 )
{
$_ul.find("label").each(
function()
{
if($(this).text().toLowerCase().charAt(0) == search.charAt(0))
{
if($(this).parent().hasClass("hide"))
$(this).parent().removeClass("hide");
if(!$_not_found.hasClass("hide"))
$_not_found.addClass("hide");
}
else
{
if(!$(this).parent().hasClass("hide"))
$(this).parent().addClass("hide");
if($_not_found.hasClass("hide"))
$_not_found.removeClass("hide");
}
}
);
}
else
{
// If it doesn't contain
if($_ul.text().toLowerCase().indexOf(search) == -1)
{
if($_not_found.hasClass("hide"))
$_not_found.removeClass("hide");
}
else
{
if(!$_not_found.hasClass("hide"))
$_not_found.addClass("hide");
}
$_ul.find("label").each(
function()
{
if($(this).text().toLowerCase().indexOf(search) > -1)
{
if($(this).parent().hasClass("hide"))
$(this).parent().removeClass("hide");
}
else
{
if(!$(this).parent().hasClass("hide"))
$(this).parent().addClass("hide");
}
}
);
}
}
);
$_submit.click(
function(e)
{
e.preventDefault();
apply();
}
);
// Delete the original form submit
$(params.selector).find('input[type=submit]').remove();
// Put finalized markup into page.
$_native_select.after($_parent_div);
// Hide the original element
$_native_select.hide();
};
</script>
</html>
/I want to use more than one form_id so I will send different paramaters to function. In the function we have selector:"#make_checkbox_select" it takes form id with # sign. And I want to send a parameter to it. I tried to
fucntion(id)
{selector: id,
.........
}
but it doesn't work.
How I can use this function for using 3 multiselect checkbox?/
This is the simple example - how you can pass parameter to the form submit handler:
var onFormSubmit = function(formId) {
alert('submit: id = ' + formId);
}
<form id="form1" onsubmit="onFormSubmit('form1')">
<input type="text" name="inputText" value="text1"/>
<button type="submit">Submit form1</button>
</form>
<form id="form2" onsubmit="onFormSubmit('form2')">
<input type="text" name="inputText" value="text2"/>
<button type="submit">Submit form2</button>
</form>

Div as Input Web/Mobile

when I open my website (https://scampsblog.com/code/openjarvis/two/index.html) a div shows up with which the user can interact (e.g. type "help"). My problem is, that when somebody opens the website on a computer, they can type as expected, but opening the website via a smartphone will prevent them from any interaction. Using contenteditable solved the smartphone issue but resulted in some weird bugs.
Here is the code I have so far:
/*
// Made with <3 by Marcus Bizal
// github.com/marcbizal
// linkedin.com/in/marcbizal
*/
$(document).ready(function() {
"use strict";
// UTILITY
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// END UTILITY
// COMMANDS
function clear() {
terminal.text("");
}
function help() {
terminal.append("There is no help... MUAHAHAHAHA. >:D\n");
}
function echo(args) {
var str = args.join(" ");
terminal.append(str + "\n");
}
function fortune() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://cdn.rawgit.com/bmc/fortunes/master/fortunes', false);
xhr.send(null);
if (xhr.status === 200) {
var fortunes = xhr.responseText.split("%");
var fortune = fortunes[getRandomInt(0, fortunes.length)].trim();
terminal.append(fortune + "\n");
}
}
// END COMMANDS
var title = $(".title");
var terminal = $(".terminal");
var prompt = "";
var path = ">";
var commandHistory = [];
var historyIndex = 0;
var command = "";
var commands = [{
"name": "clear",
"function": clear
}, {
"name": "help",
"function": help
}, {
"name": "fortune",
"function": fortune
}, {
"name": "echo",
"function": echo
}];
function processCommand() {
var isValid = false;
// Create args list by splitting the command
// by space characters and then shift off the
// actual command.
var args = command.split(" ");
var cmd = args[0];
args.shift();
// Iterate through the available commands to find a match.
// Then call that command and pass in any arguments.
for (var i = 0; i < commands.length; i++) {
if (cmd === commands[i].name) {
commands[i].function(args);
isValid = true;
break;
}
}
// No match was found...
if (!isValid) {
terminal.append("openjarvis: command not found: " + command + "\n");
}
// Add to command history and clean up.
commandHistory.push(command);
historyIndex = commandHistory.length;
command = "";
}
function displayPrompt() {
terminal.append("<span class=\"prompt\">" + prompt + "</span> ");
terminal.append("<span class=\"path\">" + path + "</span> ");
}
// Delete n number of characters from the end of our output
function erase(n) {
command = command.slice(0, -n);
terminal.html(terminal.html().slice(0, -n));
}
function clearCommand() {
if (command.length > 0) {
erase(command.length);
}
}
function appendCommand(str) {
terminal.append(str);
command += str;
}
/*
// Keypress doesn't catch special keys,
// so we catch the backspace here and
// prevent it from navigating to the previous
// page. We also handle arrow keys for command history.
*/
$(document).keydown(function(e) {
e = e || window.event;
var keyCode = typeof e.which === "number" ? e.which : e.keyCode;
// BACKSPACE
if (keyCode === 8 && e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
e.preventDefault();
if (command !== "") {
erase(1);
}
}
// UP or DOWN
if (keyCode === 38 || keyCode === 40) {
// Move up or down the history
if (keyCode === 38) {
// UP
historyIndex--;
if (historyIndex < 0) {
historyIndex++;
}
} else if (keyCode === 40) {
// DOWN
historyIndex++;
if (historyIndex > commandHistory.length - 1) {
historyIndex--;
}
}
// Get command
var cmd = commandHistory[historyIndex];
if (cmd !== undefined) {
clearCommand();
appendCommand(cmd);
}
}
});
$(document).keypress(function(e) {
// Make sure we get the right event
e = e || window.event;
var keyCode = typeof e.which === "number" ? e.which : e.keyCode;
// Which key was pressed?
switch (keyCode) {
// ENTER
case 13:
{
terminal.append("\n");
processCommand();
displayPrompt();
break;
}
default:
{
appendCommand(String.fromCharCode(keyCode));
}
}
});
// Set the window title
title.text("openjarvis setup");
// Get the date for our fake last-login
var date = ("setup");
// Display last-login and prompt
terminal.append("openjarvis " + date + " \n");
displayPrompt();
});
html,
body {
height: 100%;
overflow: hidden;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
* {
box-sizing: border-box;
}
textarea,
input,
button {
outline: none;
}
.window-button,
.window .buttons .close,
.window .buttons .minimize,
.window .buttons .maximize {
padding: 0;
margin: 0;
margin-right: 4px;
width: 12px;
height: 12px;
background-color: gainsboro;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
color: rgba(0, 0, 0, 0.5);
}
.window {
animation: bounceIn 1s ease-in-out;
width: 640px;
}
.window .handle {
height: 22px;
background: linear-gradient(0deg, #d8d8d8, #ececec);
border-top: 1px solid white;
border-bottom: 1px solid #b3b3b3;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
color: rgba(0, 0, 0, 0.7);
font-family: Helvetica, sans-serif;
font-size: 13px;
line-height: 22px;
text-align: center;
}
.window .buttons {
position: absolute;
float: left;
margin: 0 8px;
}
.window .buttons .close {
background-color: #ff6159;
}
.window .buttons .minimize {
background-color: #ffbf2f;
}
.window .buttons .maximize {
background-color: #25cc3e;
}
.window .terminal {
padding: 4px;
background-color: black;
opacity: 0.7;
height: 218px;
color: white;
font-family: 'Source Code Pro', monospace;
font-weight: 200;
font-size: 14px;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
overflow-y: auto;
}
.window .terminal::after {
content: "|";
animation: blink 2s steps(1) infinite;
}
.prompt {
color: #bde371;
}
.path {
color: #5ed7ff;
}
#keyframes blink {
50% {
color: transparent;
}
}
/*#keyframes bounceIn {
0% {
transform: translateY(-1000px);
}
60% {
transform: translateY(200px);
}
100% {
transform: translateY(0px);
}
}*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>openjarvis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="cmd.css">
</head>
<body>
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:200' rel='stylesheet' type='text/css'>
<div class="container">
<div class="window">
<div class="handle">
<div class="buttons">
<button class="close">
</button>
<button class="minimize">
</button>
<button class="maximize">
</button>
</div>
<span class="title"></span>
</div>
<div class="terminal"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" defer></script>
<script src="cmd.js" defer></script>
</body>
</html>

On Click not updating the output of a function

$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
I am trying to use a button on click event to change the temp display, but it doesn't seem to work like this. The function keeps seeing Celsius no matter what. I tried $(this).html too. The text of the button is actually changing, just the function isn't updating. I tried running the change units function inside the the button click even as well and it still doesn't update.
What am I not understanding about this onclick event and how can I get it to work.
JS Code:
var apiKey = "get your own key from http://openweathermap.org";
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
changeUnits();
});
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
var currentTemp = changeUnits(weather.main.temp);
var high = changeUnits(weather.main.temp_max);
var low = changeUnits(weather.main.temp_min);
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
$('#currentTemp').html(currentTemp);
$('#high-low').html('<span id="high">High: ' + high + '</span><br>'
+ '<span id="low">Low: ' + low + '</span>');
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"><h1 id="currentLocation">Your Current Location is </h1></div>
<div class="navbar"></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<h2 class="text-center content-title" id="currentTemp"></h2>
<div class="content-body text-center">
<p id="high-low"></p>
<button data-text-swap="Fahrenheit" id="unitButton" type="button" class="btn btn-success">Celsius</button>
<p id="currentConditions"></p>
</div>
</div>
</body>
</html>
I have done every change I can think of. console.log(el.text()) in the onclick clearly shows the text changing; but the function for changeUnits never seems to pick it up in the if statement when I run the function again during the onclick.
Looks like you're using html() instead of text(). I assume you're looking for button text instead of html, so try this:
$('.btn').on("click", function() {
$(this).text(function(f, c) {
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
});
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius'){
return Math.round(Temp - 273.15) + " &degC";
}else{
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
}
you are not calling the function, read comments in code
Also you are not passing any information to the '.btn' in the function passed to the text method.
$('.btn').on("click", function() {
var text = function(f, c) { // where are you getting your f and c parameters?
console.log(f); // should be undefined
console.log(c); // should be undefined
return c === 'Celsius' ? 'Fahrenheit' : 'Celsius';
}();
console.log(text); // should be 'Celsius'
$(this).text(text); // changed from }) to }())
});
function changeUnits(Temp, c) {
if ($('.btn').text() === 'Celsius') // change html() to text() as well
return Math.round(Temp - 273.15) + " &degC";
else
return Math.round((Temp* (9/5)) - 459.67) + " &degF";
}
Additionaly you should use a ID to associate your button to do this
<input id='thisID'>
// then call it in javascript
$("#thisID")
Toggleing the button
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
});
Here is what I think is your problem. I didn't get to test it because I need to get the weather API and stuff. By looking at your code, here is what I get.
When the page loads, you are getting weather data from OpenWeatherMap. However, you are not cashing this info in some sort of global variable in order for you to access it later. You have declared all your variables inside the ajax callback and you have no way of accessing them later.
Try to do this:
var currentTemp;
var high;
var low;
$(function() {
var loc;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
//weather API call
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' +
loc[0] + '&lon=' + loc[1] + '&appid=' + apiKey,
function(weather) {
var currentLocation = weather.name;
var currentConditions = weather.weather[0].description;
currentTemp = weather.main.temp;
high = weather.main.temp_max;
low = weather.main.temp_min;
var currentWind = weather.wind.speed;
var currentWdir = weather.wind.deg;
var sunRise = weather.sys.sunrise;
var sunSet = weather.sys.sunset;
var icon = weather.weather[0].icon;
//set HTML elements for weather info
$('#currentLocation').append(currentLocation);
updateDisplay();
$('#currentConditions').html(currentConditions);
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').prepend('Outside the current conditions are <br><img id="weatherImg"src="' + iconSrc + '"><br>');
});
});
});
function changeUnits(Temp) {
if ($('.btn').text() === 'Celsius')
return Math.round((Temp - 273.15)*10)/10 + " &degC";
else
return Math.round(((Temp* (9/5)) - 459.67)*10)/10 + " &degF";
}
$('.btn').on("click", function() {
var text = $(this).text();
$(this).text(text === 'Celsius' ? 'Fahrenheit' : 'Celsius');
updateDisplay();
});
function updateDisplay(){
$('#currentTemp').html(changeUnits(currentTemp));
$('#high-low').html('<span id="high">High: ' + changeUnits(high) + '</span><br>'
+ '<span id="low">Low: ' + changeUnits(low) + '</span>');
}
I have introduced another function updateDisplay() to actually handle the changing of the displayed temps. As I said, I didn't get to test it. But I am pretty sure it will work.
JS:
var apiKey="get an openweathermap APIKey";
var loc;
var lat;
var long;
var temp;
var high;
var low;
var icon;
//var wind;
//var windDir;
//var windSpd;
//api call to get lat and long
$.getJSON('http://ipinfo.io', function(data) {
loc = data.loc.split(",");
lat = parseFloat(loc[0]);
long = parseFloat(loc[1]);
getWeather(lat, long);
initGmaps(lat, long);
});
//api call to use lat and long to generate a map
window.addEventListener('load', function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '?key=AIzaSyDKgEmSnYmFmbhQVGY8K6NXxV5ym2yZXdc&callback=initMap';
document.body.appendChild(script);
});
function initGmaps(lat, long) {
var map = new GMaps({
div: '#map',
lat: lat,
lng: long,
zoom: 14,
disableDefaultUI: true,
mapTypeId: "satellite",
});
map.addMarker({
lat: lat,
lng: long
});
}
//using weather to get data and plug it into our page
function getWeather(lat, long) {
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
lat + '&lon=' + long + '&appid=' + apiKey;
$.ajax({
url: api,
dataType: 'json',
success: function(data) {
temp = {
f: Math.round(((data.main.temp * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp - 273.15)) * 100) / 100 + " °C"
};
high = {
f: Math.round(((data.main.temp_max * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
low = {
f: Math.round(((data.main.temp_min * 9 / 5) - 459.67) * 100) / 100 + " °F",
c: Math.round(((data.main.temp_max - 273.15)) * 100) / 100 + " °C"
};
windSpd = {
f: Math.round((data.wind.speed * 2.23694)*10)/10 + " MPH",
c: Math.round((data.wind.speed)*10)/10 + " M/S"
};
var windArr = ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
var windDir = windArr[Math.floor(((data.wind.deg/22.5)+.5))];
$('#currentLocation').append(data.name);
$('#high').append(" " + high.f);
$('#low').append(" " + low.f);
$('#currentTemp').html(temp.f);
$('#weatherDesc').html(data.weather[0].description);
$('#windDir').html(windDir);
$('#windDir').append('<span id="windSpd">' + windSpd.f + '</span>');
icon = data.weather[0].icon;
var iconSrc = "http://openweathermap.org./img/w/" + icon + ".png";
$('#currentConditions').html('<img id="weatherImg" src="' + iconSrc + '"><br>');
}
});
}
$('#currentTemp').on('click', function() {
var current = $(this).data('nexttemp');
$('#currentTemp').text(temp[current]);
$('#high').html(high[current]);
$('#low').html(low[current]);
$('#windSpd').html(windSpd[current]);
if (current == 'c') {
$(this).data('nexttemp', 'f');
return;
}
$(this).data('nexttemp', 'c');
});
HTML:
<html>
<head>
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript,width=device-width,initial-scale=1">
<title></title>
</head>
<body>
<div id="header">
<div class="left"></div>
<div class="navbar"><h4>Free Code Camp Weather App</h4></div>
<div class="right"><i class="fa fa-github bigger_icon"></i></div>
</div>
<div id="container">
<div class="col-lg-4" id="map"></div>
<div class="col-lg-4">
<h1 id="currentLocation">Your Current Location is </h1>
</div>
<h2 class="center-text content-title" id="currentTemp"></h2>
<h3 id="caption">Click temperature to change Units</h3>
<div class="center-text">
<p class="oneLine" id="labels">High: <span id="high"></span></p>
<p class="oneLine" id="labels">Low: <span id="low"></span></p>
</div>
<p class="center-text" id="currentConditions"></p>
<p class="center-text" id="weatherDesc"></p>
<div class="windCompass col-lg-4">
<div class="compass">
<div class="direction">
<p id="windDir"></p>
</div>
<div class="arrow ne"></div>
</div>
</div>
</div>
</body>
</html>
CSS:
#import url(http://fonts.googleapis.com/css?family=Dosis:200,400,500,600);
body {
background: url(http://eskipaper.com/images/pixel-backgrounds-1.jpg);
background-size: auto;
background-repeat: no-repeat;
font-family: Ranga, cursive;
}
h4 {
margin-top: 7px;
}
h1 {
margin-left: -7px;
font-size: 1.05em;
color: white;
}
#header {
background: #2980b9;
color: white;
padding: 0 5px;
display: inline-block;
width: 100%;
margin: 0;
box-shadow: 0 2px 5px #555555;
}
#header .left {
display: inline-block;
width: auto;
float: left;
margin-top: 7px;
margin-left: 7px;
}
#header .navbar {
display: inline-block;
width: 60%;
}
#header .right {
display: inline-block;
width: auto;
text-align: right;
float: right;
margin-top: 2px;
margin-right: 7px;
vertical-align: bottom;
}
.bigger_icon {
margin-top: 10px;
font-size: 2em;
color: white;
}
#map {
height: 200px;
width: 200px;
border-radius: 5%;
margin-top: 20px;
}
#container {
background: rgba(66, 66, 66, 0.6);
display: block;
position: relative;
width: 40%;
margin: 24px auto;
min-height: 300px;
padding: 16px;
border-radius: 4px;
}
#container .center-text {
text-align: center;
}
h2 {
color: white;
font-family: Ranga, cursive;
font-size: 2.5em;
font-weight: bold;
margin-top: -230px;
}
#caption {
font-size: 17px;
text-align: center;
color: pink;
}
#labels {
color: darkGrey;
font-size: 1.5em;
}
.oneLine {
color: darkGrey;
font-size: 1.5em;
text-align: center;
display: inline;
padding: 5px;
}
#high {
text-align: center;
color: orange;
}
#low {
text-align: center;
color: blue;
}
#currentConditions {
text-align: center;
color: black;
}
#weatherDesc {
margin-top: -25px;
color: white;
}
.windCompass {
margin-left: 75%;
margin-top: -20%;
}
.compass {
display: block;
width: 120px;
height: 120px;
border-radius: 100%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.85);
position: relative;
font-family: 'Dosis';
color: #555;
text-shadow: 1px 1px 1px white;
}
.compass:before {
font-weight: bold;
position: absolute;
text-align: center;
width: 100%;
content: "N";
font-size: 14px;
top: -2px;
}
.compass .direction {
height: 100%;
width: 100%;
display: block;
background: #f2f6f5;
background: -moz-linear-gradient(top, #f2f6f5 30%, #cbd5d6 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f2f6f5), color-stop(100%, #cbd5d6));
background: -webkit-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
background: o-linear-gradient(top, #f2f6f5 0%, #cbd5d6 100%);
border-radius: 100%;
}
.compass .direction p {
text-align: center;
margin: 0;
padding: 0;
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 100%;
line-height: 80px;
display: block;
margin-top: -35%;
font-size: 28px;
font-weight: bold;
}
.compass .direction p span {
display: block;
line-height: normal;
margin-top: -10%;
font-size: 17px;
text-transform: uppercase;
font-weight: normal;
font-family: Ranga, cursive;
}
.compass .arrow {
width: 100%;
height: 100%;
display: block;
position: absolute;
top: 0;
}
.compass .arrow:after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid red;
position: absolute;
top: -6px;
left: 50%;
margin-left: -5px;
z-index: 99;
}
.compass .arrow.nne {
transform: rotate(22.5deg);
}
.compass .arrow.ne {
transform: rotate(45deg);
}
.compass .arrow.ene {
transform: rotate(67.5deg);
}
.compass .arrow.e {
transform: rotate(90deg);
}
.compass .arrow.ese {
transform: rotate(112.5deg);
}
.compass .arrow.se {
transform: rotate(135deg);
}
.compass .arrow.sse {
transform: rotate(157.5deg);
}
.compass .arrow.s {
transform: rotate(180deg);
}
.compass .arrow.ssw {
transform: rotate(202.5deg);
}
.compass .arrow.sw {
transform: rotate(-135deg);
}
.compass .arrow.wsw {
transform: rotate(-114.5deg);
}
.compass .arrow.w {
transform: rotate(-90deg);
}
.compass .arrow.wnw {
transform: rotate(-69.5deg);
}
.compass .arrow.nw {
transform: rotate(-45deg);
}
.compass .arrow.nnw {
transform: rotate(-24.5deg);
}
I ended up finding some Ajax and working with it to do what I expected the button to do. While not a button, it does what is intended. I also worked in changing the high, low, and wind speed to also change with the unit change.
I appreciate the help that everyone offered.
feel free to offer suggestions on the code as well for fixing the css for the compass gradient and making the stupid thing more responsive if you'd like. (The Map is not doing the responsive thing.
Your script probably gets loaded before the DOM is ready.
What you want to do here is one of a few options:
1. Load the JS script tag at the end of the body.
2. Wrap your $('.btn').on(...) function with document.on('ready') event, so this code will only be triggered when the DOM is ready.

Categories