Javascript function in HTML not working - javascript

Dear Stackers
I am having following issue. I want to make a Website, with only one HTML file, and insert the Content based on which li element got clicked. And a standard text should already be there.
Now my issue is, that it will not change the value="" of id="content". It will not even writeContent for some reason. I am quite sure I am making a simple and fundamental mistake. I know that it is not yet optimized, but I need to get it working like this, before minimizing anything.
You can currently ignore the function writeContent part, since that will do the innerHTML insertion later on. - currently no Errors
function myHome() {
document.getElementById("content").value = "home_content";
writeContent("<p>myHome</p>");
}
function myKontakt() {
document.getElementById("content").value = "kontakt_content";
writeContent("<p>myKontakt</p>");
}
function myTeam() {
document.getElementById("content").value = "team_content";
writeContent("<p>myTeam</p>");
}
function myUber() {
document.getElementById("content").value = "uber_content";
writeContent("<p>myUber</p>");
}
document.getElementById("home_li").addEventListener("click", myHome);
document.getElementById("kontakt_li").addEventListener("click", myKontakt);
document.getElementById("team_li").addEventListener("click", myTeam);
document.getElementById("uber_li").addEventListener("click", myUber);
function writeContent() {
var get_content_attribute = document.getElementById("content").getAttribute("value");
if (document.getElementById("content").getAttribute("value") == "home_content") {
} else if (get_content_attribute = "kontakt_content") {
} else if (get_content_attribute = "team_content") {
} else if (get_content_attribute = "uber_content") {
}
}
<div id="menu">
<ul>
<li>Stalinger
</li>
<li>Kontakt
</li>
<li>Unser Team
</li>
<li>Über Uns
</li>
</ul>
</div>
<div id="content" value="home_content">
<p class="content_text">TEXT
</p>
</div>

1.Looks like div can't has value attribute, try to use "data-value"
or something like that and everything will works fine.
2. you are adding to event listeners on every button when using "click" in html and "addEventListener" in js
3. You should use "event.preventDefault()" to prevent page from reloading when pressing ""
<html>
<head></head>
<body>
<div id="menu">
<ul>
<li>Stalinger</li>
<li>Kontakt</li>
<li>Unser Team</li>
<li>Über Uns</li>
</ul>
</div>
<div id="content" data-value="home_content">
<p class="content_text">TEXT
</p>
<script>
function myHome(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"home_content");
writeContent("<p>myHome</p>");
}
function myKontakt(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"kontakt_content");
writeContent("<p>myKontakt</p>");
}
function myTeam(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"team_content");
writeContent("<p>myTeam</p>");
}
function myUber(e){
e.preventDefault();
document.getElementById("content").setAttribute('data-value',"uber_content");
writeContent("<p>myUber</p>");
}
document.getElementById("home_li").addEventListener("click", myHome);
document.getElementById("kontakt_li").addEventListener("click", myKontakt);
document.getElementById("team_li").addEventListener("click", myTeam);
document.getElementById("uber_li").addEventListener("click", myUber);
function writeContent(html) {
var div = document.getElementById("content");
var get_content_attribute = document.getElementById("content").getAttribute("data-value");
if(document.getElementById("content").getAttribute("data-value") == "home_content"){
div.innerHTML = html;
} else if(get_content_attribute = "kontakt_content"){
div.innerHTML = html;
} else if(get_content_attribute = "team_content"){
div.innerHTML = html;
} else if(get_content_attribute = "uber_content"){
div.innerHTML = html;
}
}
</script>
</div>
</body>
</html>
this code is working for me, but architecture is pretty ugly, maybe try to read about how frontend frameworks manage this things.

use setAttribute as document.getElementById("content").setAttribute ("value","XXXXXX") – by User: Vinod Louis
Worked like a charm.

You can check updated code:
To assign attribute you need to use setAttribute instead of value
function myHome() {
document.getElementById("content").setAttribute("value","home_content");
writeContent("<p>myHome</p>");
}
function myKontakt() {
document.getElementById("content").setAttribute("value","kontakt_content");
writeContent("<p>myKontakt</p>");
}
function myTeam() {
document.getElementById("content").setAttribute("value","team_content");
writeContent("<p>myTeam</p>");
}
function myUber() {
document.getElementById("content").setAttribute("value","uber_content");
writeContent("<p>myUber</p>");
}
document.getElementById("home_li").addEventListener("click", myHome);
document.getElementById("kontakt_li").addEventListener("click", myKontakt);
document.getElementById("team_li").addEventListener("click", myTeam);
document.getElementById("uber_li").addEventListener("click", myUber);
function writeContent() {
var get_content_attribute = document.getElementById("content").getAttribute("value");
alert(get_content_attribute);
if (document.getElementById("content").getAttribute("value") == "home_content") {
} else if (get_content_attribute = "kontakt_content") {
} else if (get_content_attribute = "team_content") {
} else if (get_content_attribute = "uber_content") {
}
}
<div id="menu">
<ul>
<li>Stalinger
</li>
<li>Kontakt
</li>
<li>Unser Team
</li>
<li>Über Uns
</li>
</ul>
</div>
<div id="content" value="home_content">
<p class="content_text">TEXT
</p>
</div>

Related

Save id anchor href when changing page language

Here is the case. I have a page, on which I have several options to choose. Choice is being made by clicking a link, which leads to an anchor and displays necessary content. Unfortunately this could not be changed. The problem is, that I also have a language panel, which leads me to the same page but already translated to necessary locale. My goal is to be able change language, but also save the chosen anchor from a clicked link. Was not able to find solution yet, could someone please give any idea, how that could be done?
Here is link to a fiddle https://jsfiddle.net/william_eduards/psuLrv02/87/
let contents = Array.from(document.querySelectorAll('.content'));
let contentOne = document.querySelector('.content--a');
let contentTwo = document.querySelector('.content--b');
const handleClick = (e) => {
e.preventDefault();
contents.forEach(node => {
node.classList.remove('active');
});
e.currentTarget.classList.add('active');
if (document.querySelector('.content-a').classList.contains('active')) {
contentOne.classList.add('show');
} else {
contentOne.classList.remove('show');
}
if (document.querySelector('.content-b').classList.contains('active')) {
contentTwo.classList.add('show');
} else {
contentTwo.classList.remove('show');
}
}
contents.forEach(node => {
node.addEventListener('click', handleClick);
});
.content--a, .content--b {
display: none;
}
.show {
display: block;
}
<div class="container">
<div class="select-option">
<a class="content content-a" href="#contentA">Content A</a>
<a class="content content-b" href="#contentB">Content b</a>
</div>
<div class="options">
<div class="content--a" id="contentA">
<p>I am content a</p>
</div>
<div class="content--b" id="contentB">
<p>I am content b</p>
</div>
</div>
</div>
To show your contents, just use CSS with pseudo class :target (remove all your js)
.content--a, .content--b {
display: none;
}
.options > *:target {
display: block;
}
If your page is reloaded when you select language, use sessionStorage to remember which link was last clicked, and restore it on next page load. Following code assumes the URL is unchanged when you switch languages:
window.addEventListener('DOMContentLoaded', e => {
const contents = document.querySelectorAll('.content');
//Save selection on click as url#anchor
contents.forEach(node => {
node.addEventListener('click', e => {
const href = node.getAttribute('href');
console.log(href);
if (href) {
const spl = href.split('#');
if (spl.length > 1 && spl[1].length) {
const spl2 = window.location.href.split('#');
sessionStorage.setItem('shown-content', spl2[0] + '#' + spl[1]);
console.log(sessionStorage.getItem('shown-content'));
}
}
});
});
//Restore selection on load if URL is the same up until anchor
const anch = sessionStorage.getItem('shown-content');
if (anch) {
const spl = anch.split('#');
if (spl.length) {
const spl2 = window.location.href.split('#');
console.log(spl[0], spl2[0]);
if (spl[0] == spl2[0])
window.location.href = anch;
}
}
});
Adapt above code to your needs if URL changes between languages
Full example (doesn't run as a snippet. Use server or local html file)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Test</title>
<style>
.content--a, .content--b {
display: none;
}
.options > *:target {
display: block;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', e => {
const contents = document.querySelectorAll('.content');
//Save selection on click as url#anchor
contents.forEach(node => {
node.addEventListener('click', e => {
const href = node.getAttribute('href');
console.log(href);
if (href) {
const spl = href.split('#');
if (spl.length > 1 && spl[1].length) {
const spl2 = window.location.href.split('#');
sessionStorage.setItem('shown-content', spl2[0] + '#' + spl[1]);
console.log(sessionStorage.getItem('shown-content'));
}
}
});
});
//Restore selection on load if URL is the same up until anchor
const anch = sessionStorage.getItem('shown-content');
if (anch) {
const spl = anch.split('#');
if (spl.length) {
const spl2 = window.location.href.split('#');
console.log(spl[0], spl2[0]);
if (spl[0] == spl2[0])
window.location.href = anch;
}
}
});
</script>
</head>
<body>
<div class="container">
<div class="languages">
English
Français
</div>
<div class="select-option">
<a class="content content-a" href="#contentA">Content A</a>
<a class="content content-b" href="#contentB">Content b</a>
</div>
<div class="options">
<div class="content--a" id="contentA">
<p>I am content a</p>
</div>
<div class="content--b" id="contentB">
<p>I am content b</p>
</div>
</div>
</div>
</body>
</html>
You can simply save the element which is active. No big deal.
let contents = Array.from(document.querySelectorAll('.content'));
...
let activeEl = null;
const handleClick = (e) => {
...
e.currentTarget.classList.add('active');
activeEl = e.currentTarget; // adding the `<a/>` tag in a global
...
}

Javascript snipet error in render function in a react application - '}' expected

I am writing a simple react code that has a certain portion of javascript which is throwing me an error
var React = require('react');
var Link = require('react-router').Link;
var openColumnAnalysis = React.createClass({
render: function(){
return(
<body>
<div>
<Link to={"/"}>Reports Home</Link>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Reports.."></input>
<ul id="myUL">
<li>
Map Report
</li>
<li>
Customer Report
</li>
</ul>
</div>
<script>
function myFunction()
{
// document.write("Hi")
filter = document.getElementById('myInput').value
li_tag = document.getElementById('myUL').getElementsByTagName('li')
for (i = 0; i < li_tag.length; i++)
{
a_tag = li_tag[i].getElementsByTagName('a')[0];
if (a_tag.innerHTML.toUpperCase().indexOf(filter) > -1)
{
li_tag[i].style.display = "";
}
else
{
li_tag[i].style.display = "none";
}
}
}
</script>
</body>
);
}
});
module.exports = openColumnAnalysis;
the 'document.write("Hi")' statement works perfectly. But even if I just write 'var inp;' and nothing else.. I start getting an error like '} expected'!
I don't understand where this is going wrong... I am following this link : https://www.w3schools.com/howto/howto_js_filter_lists.asp for this learning.
Edit: Pasting my code as ref as asked.. :) If I remove the script tag, then the code runs fine... but I am trying to filter the li tags here based on search input..
Thanking you in advance!
Thank you for your help, but I got an answer here. For some reason I am not sure script tags are not working when defined inside the return statement of any react function. So I created another function to perform the filtering and called the same in the render function as below:
filterRepo: function(){
return(
function myFunction() {
var filter = document.getElementById('myInput').value.toUpperCase();
var li = document.getElementById("myUL").getElementsByTagName('li');
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
);
},
render: function(){
var repoLink = this.state.repoLinks;
repoLink = repoLink.map(function(item, index){
return(
<OpenReport key={index} desc={item.description} );
}.bind(this));
return(
<div id="inside_repoInfo">
<br></br>
<input type="text" id="myInput" onKeyUp={this.filterRepo()} placeholder="Search for Report.."></input>
<ul id="myUL" >{repoLink}</ul>
</div>
);
}
The rest of the code if only to display the list tag which I have defined in OpenReport component.
Hope this helps others!

Javascript innerHTML animation

I have a Countdown in Javascript and HTML. Its working through innerHTML and I want a animation when changing the values from innerHTML.
Countdown is working perfectly!
Javascript:
var jahr=2016, monat=5, tag=15, stunde=11, minute=2, sekunde=00; var zielDatum=new Date(jahr,monat-1,tag,stunde,minute,sekunde); function countdown() {
startDatum=new Date(); // Aktuelles Datum
if(startDatum<zielDatum) {
var jahre=0, monate=0, tage=0, stunden=0, minuten=0, sekunden=0;
while(startDatum<zielDatum) {
jahre++;
startDatum.setFullYear(startDatum.getFullYear()+1);
}
startDatum.setFullYear(startDatum.getFullYear()-1);
jahre--;
while(startDatum<zielDatum) {
monate++;
startDatum.setMonth(startDatum.getMonth()+1);
}
startDatum.setMonth(startDatum.getMonth()-1);
monate--;
while(startDatum.getTime()+(24*60*60*1000)<zielDatum) {
tage++;
startDatum.setTime(startDatum.getTime()+(24*60*60*1000));
}
stunden=Math.floor((zielDatum-startDatum)/(60*60*1000));
startDatum.setTime(startDatum.getTime()+stunden*60*60*1000);
minuten=Math.floor((zielDatum-startDatum)/(60*1000));
startDatum.setTime(startDatum.getTime()+minuten*60*1000);
sekunden=Math.floor((zielDatum-startDatum)/1000);
(jahre!=1)?jahre=jahre+"":jahre=jahre+"";
(monate!=1)?monate=monate+"":monate=monate+"";
(tage!=1)?tage=tage+"":tage=tage+"";
(stunden!=1)?stunden=stunden+"":stunden=stunden+"";
(minuten!=1)?minuten=minuten+"":minuten=minuten+"";
if(sekunden<10) sekunden="0"+sekunden;
(sekunden!=1)?sekunden=sekunden+"":sekunden=sekunden+"";
document.getElementById('days').innerHTML = ""+tage+"";
document.getElementById('hours').innerHTML = ""+stunden+"";
document.getElementById('minutes').innerHTML = ""+minuten+"";
document.getElementById('seconds').innerHTML = ""+sekunden+"";
if(tage==1){
dayText = "Tag";
} else {
dayText = "Tage";
}
if(stunden==1){
hoursText = "Stunde";
} else {
hoursText = "Stunden";
}
if(minuten==1){
minutesText = "Minute";
} else {
minutesText = "Minuten";
}
if(sekunden==1){
secondsText = "Sekunde";
} else {
secondsText = "Sekunden";
}
document.getElementById('daysText').innerHTML = ""+dayText+"";
document.getElementById('hoursText').innerHTML = ""+hoursText+"";
document.getElementById('minutesText').innerHTML = ""+minutesText+"";
document.getElementById('secondsText').innerHTML = ""+secondsText+"";
setTimeout('countdown()',200);
} else {
}
}
HTML:
<div class="time days">
<div id="days" class="value">00</div>
<div id="daysText" class="unit">Days</div>
</div>
<div class="time hours">
<div id="hours" class="value">00</div>
<div id="hoursText" class="unit">Hours</div>
</div>
<div class="time minutes">
<div id="minutes" class="value">00</div>
<div id="minutesText" class="unit">Minutes</div>
</div>
<div class="time seconds">
<div id="seconds" class="value">00</div>
<div id="secondsText" class="unit">Seconds</div>
</div>
And how can I do for example a fadeInDown animation?
Thanks!
The easiest way to do this would probably be JQuery, found at JQuery.com.
I also found a similar question here: jquery animation on div innerhtml on change
As for your code, you'll want something like:
$('#daysText').fadeOut(1000, function()
{
$(this).html(dayText).fadeIn(1000);
});
$('#hoursText').fadeOut(1000, function()
{
$(this).html(hoursText).fadeIn(1000);
});
$('#minutesText').fadeOut(1000, function()
{
$(this).html(minutesText).fadeIn(1000);
});
$('#secondsText').fadeOut(1000, function()
{
$(this).html(secondsText).fadeIn(1000);
});
Note that this will only work with JQuery installed. Instructions to this can be found at http://jquery.com/download/
Short version of said instructions: Add the following code to your HTML (Commonly done near the bottom of the document) to include the JQuery library
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You can't animate a text-node directly.
You'll have to animate a wrapping element, which will have dynamically set style values. Something like:
<span style="opacity:0;">your content</span>
Also, changing innerHTML is a complete replacement of existing elements, it will "break" any ongoing animations inside the parent element.

innerHTML output with Javascript template

For my project I have to scan BLE-tags and show their RSSI for proximity.
The output of the BLEs is working with a JavaScript template.
<body>
<div id="header" data-role="header" data-theme="b">
<h1>BLE overview</h1>
</div>
</br>
<div data-role="content" id="home">
Initialize
Start Scan
Stop Scan
</div>
<ul data-role="list-view" class="devices"></ul>
<div data-role="content id="result">
<script type="text/template" id="device"> //start of the schript tag and output of the scanned BLEs
<ul data-role="listview">
<li data-address="{0}">
<h2>{1}</h2>
Connect
<div id="rssiop"> RSSI: <div> // value of the RSSI
</br>
</li>
</ul>
</script>
</div>
The function, which return the value of the rssi is following
function startScanSuccess(obj)
{
console.log("The RSSI value is:" + obj.rssi); // here I see the RSSI value on the console
if (obj.status == "scanResult")
{
console.log("Scan Result");
addDevice(obj.address, obj.name);
}
else if (obj.status == "scanStarted")
{
console.log("Scan Started");
}
else
{
console.log("Unexpected Start Scan Status");
}
}
and this is the function which gives the name and address of the scanned BLE out
function addDevice(address, name)
{
var $devices = $(".devices");
var $check = $devices.find("li[data-address='{0}']".format(address));
if ($check.length > 0)
{
return;
}
console.log("Mein RSSI: " + obj.rssi);
document.getElementById("rssiop").innerHTML = "The RSSI value is:";
var template = $("#device").text().format(address, name);
$devices.append(template);
}
So everything is working and when I put the div-tag above the template script I can see the RSSI. Can anyone figure out why the innerHTML is in the template part not working?
I figured it out:
The Problem was that the innerHTML wasn't working, because I used the append()-command for the list output. I just had to add the rssi parameter to the addDevices function and it worked.
The correct code of the addDevice function:
function addDevice(address, name, rssi)
{
var $devices = $(".devices");
var $check = $devices.find("li[data-address='{0}']".format(address));
if ($check.length > 0)
{
return;
}
var template = $("#device").text().format(address, name, rssi);
$devices.append(template);
}

how to get the inside id using jquery?

I want to assign values to inside id how can i do that in Jquery
controller.cs code
public GroupModel Get()
{
IGroupTypeRepository groupTypeRepo = new GroupTypeRepository();
IGroupRepository groupRepo = new GroupRepository();
var model = new GroupModel();
model.GroupTypes = groupTypeRepo.GetAll().ToList();
Guid first = model.GroupTypes.FirstOrDefault().Id;
model.Groups = groupRepo.GetAll().Where(s => s.Type == first).ToList();
return model;
}
I tried like following
function getGroups() {
debugger;
$.getJSON(
"groupvalues",
function (data) {
if (data.GroupTypes != undefined) {
$.each(data.Groups, function (jindex, jvalue) {
debugger;
if (jvalue.Id != undefined) {
$("#GroupsTemplate").tmpl(jvalue).appendTo(".span9 .row #projects");
}
});
}
}
<div class="span9">
<div class="row">
<section id="projects">
</section>
</div>
</div>
<script id="GroupsTemplate" type="text/html">
<ul id="thumbs">
<li class="item-thumbs span3 Dhol">
<span class="font-icon-music"></span>${GroupType.TypeName}<br />
</p></div> </li>
</ul>
</script>
I guess i'm going wrong here in js function
$("#GroupsTemplate").tmpl(jvalue).appendTo(".span9 .row #projects");
I think that instead of this:
${GroupType.TypeName}
you must have only this:
${TypeName}
because the GroupType is the parameter object for the template (implicit).
Hope this helps. Cheers

Categories

Resources