How to hide previous data? - javascript

Im doing some basic programming of Javascript and jquery.. Please run the snippet first to see the output.(cant post image :()
When i click 'saga' it append the information of saga.. later, if i click persona it append persona below of the existed data. I want it to be like this-When i click persona the previous data will vanish and replaced with new one.
my code:
Javascript
function myCar(carName, carPlate, carColor) {
this.carName = carName;
this.carPlate = carPlate;
this.carColor = carColor;
};
var Saga = new myCar('Saga', 'BLM2222', 'blue'),
Persona = new myCar('Persona', 'JKQ2390', 'red'),
Wira = new myCar('Wira','GVB3450','violet');
myCar.prototype.details = function($div){
$div.append('Car Name: ' + this.carName + '<br>' + 'Car Plate: ' + this.carPlate + '<br>' + 'Car Color:' + this.carColor + '<br>' + '<br>');
};
$(document).ready(function() {
$('#cars').click(function(e) {
var cars = $(e.target);
switch(cars[0].id) {
case 'sagabtn':
Saga.details($('#bigdiv'));
break;
case 'sonabtn':
Persona.details($('#bigdiv'));
break;
case 'wirabtn':
Wira.details($('#bigdiv'));
break;
}
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Proton</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="app.js"></script>
<!--<link rel="stylesheet" type="text/css" href="stylesheet.css"/>-->
</head>
<body>
<h1>Proton Cars</h1>
<div id="cars">
<button id="sagabtn">Saga</button>
<br><br>
<button id="sonabtn">Persona</button>
<br><br>
<button id="wirabtn">Wira</button>
<br><br>
</div>
<div id="bigdiv"></div>
</body>
</html>

Instead of using .append you can use .html. .append will add to the DOM. .html will replace the html.
Read these articles: http://api.jquery.com/html/ http://api.jquery.com/append/
function myCar(carName, carPlate, carColor) {
this.carName = carName;
this.carPlate = carPlate;
this.carColor = carColor;
};
var Saga = new myCar('Saga', 'BLM2222', 'blue'),
Persona = new myCar('Persona', 'JKQ2390', 'red'),
Wira = new myCar('Wira','GVB3450','violet');
myCar.prototype.details = function($div){
$div.html('Car Name: ' + this.carName + '<br>' + 'Car Plate: ' + this.carPlate + '<br>' + 'Car Color:' + this.carColor + '<br>' + '<br>');
};
$(document).ready(function() {
$('#cars').click(function(e) {
var cars = $(e.target);
switch(cars[0].id) {
case 'sagabtn':
Saga.details($('#bigdiv'));
break;
case 'sonabtn':
Persona.details($('#bigdiv'));
break;
case 'wirabtn':
Wira.details($('#bigdiv'));
break;
}
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Proton</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="app.js"></script>
<!--<link rel="stylesheet" type="text/css" href="stylesheet.css"/>-->
</head>
<body>
<h1>Proton Cars</h1>
<div id="cars">
<button id="sagabtn">Saga</button>
<br><br>
<button id="sonabtn">Persona</button>
<br><br>
<button id="wirabtn">Wira</button>
<br><br>
</div>
<div id="bigdiv"></div>
</body>
</html>

You can use document.getElementById("bigdiv").textContent = ""; to clear on each button press

Related

How to set CSS using JSON data retrieved with Javascript

I am working on an dynamic HTML document that has to change its styling based on Google Sheets entries. So far it loads the JSON data just fine. I have been looking for a way to style the CSS so I can change it on the fly. Is there anyone that can point me in the right direction?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Google Sheets</title>
<style>
</style>
<script type="text/javascript">
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://spreadsheets.google.com/feeds/cells/1d3z-eJz2X_rFhq3a1kQ6TRlxJqHvstLQ/1/public/full?alt=json')
ourRequest.onload = function () {
var ourData = JSON.parse(ourRequest.responseText);
var adTekst = ourData.feed.entry[6].gs$cell.inputValue;
var achtergrondKleur = ourData.feed.entry[7].gs$cell.inputValue;
var tekstKleur = ourData.feed.entry[8].gs$cell.inputValue;
console.log(adTekst);
console.log(achtergrondKleur);
console.log(tekstKleur);
document.getElementById('testoutput').innerHTML = adTekst + " " + achtergrondKleur + " " + tekstKleur;
};
ourRequest.send();
</script>
</head>
<body>
<div id="testoutput"></div>
</body>
</html>
You can do that by toggling classes using javascript.
document.getElementById('testoutput').classList.toggle('myClass');
Other way is to change individual CSS properties
document.getElementById('testoutput').style.backgroundColor = 'RED';
Yes you can, you also give specific css to all columns with using html tags. See snippet below
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Google Sheets</title>
<style>
</style>
<script type="text/javascript">
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://spreadsheets.google.com/feeds/cells/1dLbBxSuyGxbG3z-eJz2X_rFhq3a1kQ6TRlxJqHvstLQ/1/public/full?alt=json')
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
var adTekst = ourData.feed.entry[6].gs$cell.inputValue;
var achtergrondKleur = ourData.feed.entry[7].gs$cell.inputValue;
var tekstKleur = ourData.feed.entry[8].gs$cell.inputValue;
console.log(adTekst);
console.log(achtergrondKleur);
console.log(tekstKleur);
document.getElementById('testoutput').innerHTML ='<span>'+adTekst+'</span>'+ " " + '<span>'+achtergrondKleur+'</span>' + " " + tekstKleur;
};
ourRequest.send();
</script>
</head>
<style>
div#testoutput { color: red;}
div#testoutput span { color: blue;}
div#testoutput span:first-child {color: aqua;}
</style>
<body>
<div id="testoutput"></div>
</body>
</html>
You can give color or design as per your requirement.

How to use Templates on javascript?

I Have A function that add html to a div.
var user = $("#ddlUser").val();
var role = $("#ddlUserRole").val();
var html = '<div class="calendaruser">';
html += '<span>' + user + '</span> <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
html += '<div>' + role + '</div>';
html += '</div>';
$("#divCalendarUsers").append(html);
i'm looking for a better way to use the template.
You can use the template literal:
A little sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Array2Table</title>
</head>
<body>
<div id="tableContent"></div>
<script>
var country = ["Country1", "Country2", "Country3"];
var capital = ["City1", "City2" , "City3"];
const tmpl = (country,capital) => `
<table><thead>
<tr><th>Country<th>Capital<tbody>
${country.map( (cell, index) => `
<tr><td>${cell}<td>${capital[index]}</tr>
`).join('')}
</table>`;
tableContent.innerHTML=tmpl(country, capital);
</script>
</body>
</html>
To use template in javascript, try handlebarsjs.
I male a function that creates the element taking two arguments (role and user).The return of this function you can bind it in every DOM element you want
function createTemplate(user,role){
var divCalendar=$('<div class="calendaruser"></div>');
var buttonElm=$('<button type="button" class="btn btn-default btn-xs">הסר משתמש</button>');
var spanElm=$('<span>'+user+'</span>');
var divELm=$('<div>'+role+'</div>');
divCalendar.append(buttonElm).append(spanElm).append(divELm);
return divCalendar;
}
//Example below:
$('body').append(createTemplate('user_value', 'role_value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Displaying multiple user outputs using JavaScript

I am trying to display multiple user outputs, so that when something is entered in the text field, it is captured and displayed in the div.
At the moment it keeps overwriting with the new result rather than adding to what is already displayed.
Can anyone help with this?
HTML:
<!DOCTYPE HTML>
<html lang="en">
<!-- more meta data needs to go in here -->
<head>
<script type="text/javascript" src="main_app_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="">
<meta charset="UTF-8">
<title>List Check</title>
</head>
<body>
<input type="text" id="enter_box">
<button onclick="output_function()"> Add To List </button>
<div id="list_output"></div>
</body>
JavaScript:
function output_function() {
var user_input = document.getElementById("enter_box").value;
document.getElementById("list_output").innerHTML = user_input;
}
Do
document.getElementById("list_output").innerHTML += user_input + '<br />';
instead.
This will concatenate your value and add a line break at the end of the text, to create a "list". Notice the =+ and + '<br /> differences.
You could also try this
function output_function() {
'use strict';
var user_input = document.getElementById("enter_box").value;
var list_output = document.getElementById("list_output");
if( list_output.innerHTML === '' ) {
list_output.innerHTML = '<p>' + user_input + '</p>';
} else {
list_output.innerHTML += '<p>' + user_input + '</p>';
}
}

Reading <input> values from an iframe and sending it to another as HTML

How should I read values from iframe1 and send it to iframe2 as HTML? Either JavaScript or jQuery is acceptable - it does not matter. I'm new to javascript. I already found code like the one below, maybe this will help.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function getIframeText() {
var iframe0 = document.getElementById("iframe0");
var iframe0document=iframe0.contentDocument||iframe0.contentWindow.document;
var inputIframe = iframe0document.getElementById("frame_text");
alert(inputIframe.value);
}
</script>
</head>
<body>
<div>
<button onclick="getIframeText()">get iframe text</button>
<iframe id="iframe0" src="test.html" >
<input type=text id="parent_text">
</div>
</body>
</html>
Take a look to this: http://jsfiddle.net/nick_craver/c5JeU/2/
$('button').click(function(){
var fjq = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');
f.append( '----------<br>');
f.append( 'test1: ' + fjq.data(f[0], 'test1') + '<br>test2: ' + fjq.data(f[0], 'test2') + '<br>' );
f.append( 'test3: ' + typeof (fjq.data(f[0], 'test3')) + '<br>' );
})
I found it on: Access jQuery data from iframe element

What's the simplest way to create a score counter and leaderboard for my android app game?

I'll try and make this as understandable as I can,my app designed and developed using a cloud based app maker is a multiple choice sports game. The HTML, CSS and JavaScript layout and buttons are completed but I want to add the finishing touches.
I have the basic code for when the user clicks the correct button so the score increases I think.... (I just need to change it so it works within my game.)
<div id="output">0</div>
$('#target1').click(function(){
$('#output').html(function(i, val){
return val * 1 + 1 });
});
and I know for incorrect its...
$('#target2').click(function(){
$('#output').html(function(i, val){
return val * 1 - 1 });
});
But first I am stuck on how to carry the score from question 1 over to all the other questions so that it increases/decreases then I'm not sure how to create a simple leaderboard once the games finished. My final problem will be where to place the code correctly as well. The easiest or simplest way will be very much appreciated, thank you for taking the time to read this.
Tiggzi HTML code is this...
<head>
<script type="text/javascript" src="res/lib/detectmobilebrowser.js">
</script>
<script type="text/javascript">
var screen_mobile = true;
var screen_width = 320;
var screen_height = 480;
var browser_mobile = is_mobile_browser();
if (screen_mobile && !browser_mobile && top == window)
{
top.location.href = './mob-screen-B626.html';
}
</script>
<title>
Question 1
</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta names="apple-mobile-web-app-status-bar-style" content="black-translucent"
/>
<link type="text/css" href="res/lib/jquerymobile/1.0/jquery.mobile-1.0.css" rel="stylesheet"
/>
<link type="text/css" href="files/views/assets/asset-1312828" rel="stylesheet" />
<script type="text/javascript" src="res/lib/store/json2.js">
</script>
<script type="text/javascript" src="res/lib/jquery/jquery-1.6.4.js">
</script>
<script type="text/javascript" src="res/lib/jquerymobile/jquery.mobile.iepatch.js">
</script>
<script type="text/javascript" src="res/lib/jquerymobile/1.0/jquery.mobile-1.0.js">
</script>
<script type="text/javascript" src="res/lib/mobilebase.js">
</script>
<script type="text/javascript" src="res/lib/store/jstore.js">
</script>
<script type="text/javascript" src="res/lib/event/customEventHandler.js">
</script>
<script type="text/javascript" src="res/lib/base/sha1.js">
</script>
<script type="text/javascript" src="res/lib/base/oauth.js">
</script>
<script type="text/javascript" src="res/lib/base/contexts.js">
</script>
<script type="text/javascript" src="res/lib/base/jsonpath.js">
</script>
<script type="text/javascript" src="res/lib/base/jquery.xml2json.min.js">
</script>
<script type="text/javascript" src="res/lib/base/api.js">
</script>
<script type="text/javascript" src="res/lib/base/impl.js">
</script>
<script type="text/javascript" src="res/lib/phonegap.js">
</script>
<script type="text/javascript" src="res/lib/childbrowser.js">
</script>
<script type="text/javascript" src="res/lib/barcodescanner.js">
</script>
<link href="res/css/mobilebase.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script language="JavaScript" type="text/javascript">
if (navigator.userAgent.match(/iP/i))
{
$(window).bind('orientationchange', function(event)
{
$('meta[name="viewport"]').attr('content', 'initial-scale=1.0,maximum-scale=1.0, ' + ((window.orientation == 90 || window.orientation == -90 || window.orientation == 270) ? "height=device-width,width=device-height" : "height=device-height,width=device-width"));
}).trigger('orientationchange');
}
</script>
<div data-role="page" style="min-height:480px;" id="j_38" class="type-interior">
<div data-role="header" data-position="fixed" data-theme='a' data-add-back-btn="false"
name="mobileheader2" id="j_40" class='mobileheader4'>
<h1 dsid="mobileheader2">
Question 1
</h1>
</div>
<div data-role="content" id="j_41" name="mobilecontainer2" class="mobilecontainer4"
dsid="mobilecontainer2" data-theme='b'>
<link href="screen-B626.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="screen-B626.js">
</script>
<div name="mobilelabel1" id="j_42" dsid="mobilelabel1" data-role="tiggr_label" class='mobilelabel3'>
Who won the Barclays Premier League from 1993-1994?
</div>
<div class="mobilebutton7_wrapper ">
<a data-role="button" name="BR" dsid="BR" class=' mobilebutton7' id='j_43' data-inline='false'
data-theme='a' tabIndex="1">Blackburn Rovers</a>
</div>
<div class="mobilebutton8_wrapper ">
<a data-role="button" name="AR" dsid="AR" class=' mobilebutton8' id='j_44' data-inline='false'
data-theme='a' tabIndex="2">Arsenal</a>
</div>
<div class="mobilebutton9_wrapper ">
<a data-role="button" name="MU" dsid="MU" class=' mobilebutton9' id='j_45' data-inline='false'
data-theme='a' tabIndex="3">Manchester Utd</a>
</div>
<div class="mobilebutton10_wrapper ">
<a data-role="button" name="LI" dsid="LI" class=' mobilebutton10' id='j_46' data-inline='false'
data-theme='a' tabIndex="4">Liverpool</a>
</div>
<div class="mobilebutton11_wrapper ">
<a data-role="button" name="Home" dsid="Home" class=' mobilebutton11' id='j_47'
data-icon='arrow-l' data-iconpos='left' data-inline='false' data-theme='a' tabIndex="5">Home</a>
</div>
</div>
</div>
</body>
JavaScript code is this...
/*
* JS for Question 1 generated by Exadel Tiggzi
*
* Created on: Sunday, February 26, 2012, 02:05:40 PM (PST)
*/
/************************************
* JS API provided by Exadel Tiggzi *
************************************/
/* Setting project environment indicator */
Tiggr.env = "apk"; /* Object & array with components "name-to-id" mapping */
var n2id_buf = {
'mobilecontentlayer6': 'j_13',
'mobileheader6': 'j_14',
'mobilecontainer6': 'j_15',
'mobilelabel3': 'j_16',
'mobilefooter6': 'j_17',
'annotationslayer6': 'j_18',
'mobilelabel1': 'j_42',
'BR': 'j_43',
'AR': 'j_44',
'MU': 'j_45',
'LI': 'j_46',
'Home': 'j_47'
};
if ("n2id" in window && n2id != undefined) {
$.extend(n2id, n2id_buf);
} else {
var n2id = n2id_buf;
}
function pageItem(pageName, pageLocation) {
this.name = pageName;
this.location = pageLocation;
}
Tiggr.AppPages = [
new pageItem('Question 5 ', 'screen-D8D7.html'), new pageItem('Incorrect!!!', 'screen- B60E.html'), new pageItem('News', 'screen-5FA9.html'), new pageItem('T&C', 'screen-A553.html'), new pageItem('Question 1 ', 'screen-B626.html'), new pageItem('Question 4 ', 'screen-5661.html'), new pageItem('Question 3 ', 'screen-BFDF.html'), new pageItem('Home', 'screen-1865.html'), new pageItem('Question 2 ', 'screen-4717.html'), new pageItem('current', 'screen-B626.html')];
function navigateTo(outcome, useAjax) {
Tiggr.navigateTo(outcome, useAjax);
}
function adjustContentHeight() {
Tiggr.adjustContentHeight();
}
function adjustContentHeightWithPadding() {
Tiggr.adjustContentHeightWithPadding();
}
function unwrapAndApply(selector, content) {
Tiggr.unwrapAndApply(selector, content);
}
function setDetailContent(pageUrl) {
Tiggr.setDetailContent(pageUrl);
}
/*********************
* GENERIC SERVICES *
*********************/
/*************************
* NONVISUAL COMPONENTS *
*************************/
var datasources = [];
/************************
* EVENTS AND HANDLERS *
************************/
// screen onload
screen_B626_onLoad = j_38_onLoad = function() {
createSpinner("res/lib/jquerymobile/images/ajax-loader.gif");
Tiggr.__registerComponent('mobilecontentlayer6', new Tiggr.BaseComponent({
id: 'mobilecontentlayer6'
}));
Tiggr.__registerComponent('mobileheader6', new Tiggr.BaseComponent({
id: 'mobileheader6'
}));
Tiggr.__registerComponent('mobilecontainer6', new Tiggr.BaseComponent({
id: 'mobilecontainer6'
}));
Tiggr.__registerComponent('mobilelabel3', new Tiggr.BaseComponent({
id: 'mobilelabel3'
}));
Tiggr.__registerComponent('mobilefooter6', new Tiggr.BaseComponent({
id: 'mobilefooter6'
}));
Tiggr.__registerComponent('annotationslayer6', new Tiggr.BaseComponent({
id: 'annotationslayer6'
}));
Tiggr.__registerComponent('mobilelabel1', new Tiggr.BaseComponent({
id: 'mobilelabel1'
}));
Tiggr.__registerComponent('BR', new Tiggr.BaseComponent({
id: 'BR'
}));
Tiggr.__registerComponent('AR', new Tiggr.BaseComponent({
id: 'AR'
}));
Tiggr.__registerComponent('MU', new Tiggr.BaseComponent({
id: 'MU'
}));
Tiggr.__registerComponent('LI', new Tiggr.BaseComponent({
id: 'LI'
}));
Tiggr.__registerComponent('Home', new Tiggr.BaseComponent({
id: 'Home'
}));
for (var idx = 0; idx < datasources.length; idx++) {
datasources[idx].__setupDisplay();
}
adjustContentHeightWithPadding();
j_38_deviceEvents();
j_38_windowEvents();
screen_B626_elementsExtraJS();
screen_B626_elementsEvents();
}
// screen window events
screen_B626_windowEvents = j_38_windowEvents = function() {}
// device events
j_38_deviceEvents = function() {
document.addEventListener("deviceready", function() {
adjustContentHeightWithPadding();
});
}
// screen elements extra js
screen_B626_elementsExtraJS = j_38_elementsExtraJS = function() {
// screen (screen-B626) extra code
}
// screen elements handler
screen_B626_elementsEvents = j_38_elementsEvents = function() {
$("a :input,a a,a fieldset label").live({
click: function(event) {
event.stopPropagation();
}
});
$('[name="BR"]').die().live({
vclick: function() {
if (!$(this).attr('disabled')) {
Tiggr.navigateTo('Incorrect!!!', {
transition: 'pop'
});
}
},
});
$('[name="AR"]').die().live({
vclick: function() {
if (!$(this).attr('disabled')) {
Tiggr.navigateTo('Incorrect!!!', {
transition: 'pop'
});
}
},
});
$('[name="MU"]').die().live({
vclick: function() {
if (!$(this).attr('disabled')) {
Tiggr.navigateTo('Question 2 ', {
transition: 'slide',
reverse: false
});
}
},
});
$('[name="LI"]').die().live({
vclick: function() {
if (!$(this).attr('disabled')) {
Tiggr.navigateTo('Incorrect!!!', {
transition: 'pop'
});
}
},
});
$('[name="Home"]').die().live({
vclick: function() {
if (!$(this).attr('disabled')) {
Tiggr.navigateTo('Home', {
transition: 'slide',
reverse: false
});
}
},
});
}
$("body").undelegate("pagebeforeshow").delegate("#j_38", "pagebeforeshow", function(event, ui) {
j_38_onLoad();
});
Many thanks if you are going to reply, I've tried my best searching and testing to get this score counter and leader board but I found it difficult to get results or anything basic.

Categories