HTML Div not Showing - html

I have a query: My HTML code shows some SVG gauge(taken from google-chartdiv), I want to display it twice on my page but it appears on first time and after that no matter how many I place in HTML code it does not show. How to display it for multiple times in one HTML page. Please advise.
<div class="col-md-3">
<div class="row no-gutter">
<div class="col-md-12 gage">
<h1>Avg Handle Time (Sec)</h1>
<div id="chartdiv" style="width:350px; height:300px;"></div>
<span>#ViewBag.Name</span>
</div>
<div class="col-md-6">
<div class="row no-gutter">
<div class="col-md-12 gage">
<h1>Service Level %</h1>
<div id="chartdiv" style="width:350px; height:300px;"></div>
<span>#ViewBag.Age</span>
</div>
My chartdiv code is:
<script>
var chart;
var arrow;
var axis;
AmCharts.ready(function () {
// create angular gauge
chart = new AmCharts.AmAngularGauge();
chart.addTitle("Speedometer");
// In gauge.js has Nailradius , set the circular bottom of needle from there
// create axis
axis = new AmCharts.GaugeAxis();
axis.startValue = 0;
axis.axisThickness = 5;
axis.valueInterval = 50;
axis.endValue = 300;
// color bands
var band1 = new AmCharts.GaugeBand();
band1.startValue = 0;
band1.endValue = 180;
band1.innerRadius = "94%"; // The thickness of Color Scheme lesser % = thick color
band1.color = "#00CC00";
var band2 = new AmCharts.GaugeBand();
band2.startValue = 180;
band2.endValue = 240;
band2.color = "#ffac29";
band2.innerRadius = "94%"; // The thickness of Color Scheme lesser % = thick color
var band3 = new AmCharts.GaugeBand();
band3.startValue = 240;
band3.endValue = 300;
band3.color = "#ea3838";
band3.innerRadius = "94%"; // The thickness of Color Scheme lesser % = thick color
axis.bands = [band1, band2, band3];
// bottom text
axis.bottomTextYOffset = -20;
axis.setBottomText("0 km/h");
chart.addAxis(axis);
// gauge arrow
arrow = new AmCharts.GaugeArrow();
arrow.color = "#0000"; // Arrow color set to Black
arrow.startWidth = "10"; //This is the width of Arrow connection with Base Circle
arrow.radius = "100"; // This is the area covered by needle during motion
chart.addArrow(arrow);
chart.write("chartdiv1");
// change value every 2 seconds
setInterval(randomValue, 2000);
});
// set random value
function randomValue() {
var value = Math.round(Math.random() * 200);
arrow.setValue(value);
axis.setBottomText(value + " km/h");
}
</script>

The Problem was with the CSS scripts referred in HTML file. I was giving wrong Paths of CSS file having my SVG gauge. One path was correct while other was not pointing Correct.

Related

Line chart not displaying correctly within modal box

I am new to HTML jquery. I'm stuck on the below issue and unsure not sure how to go about solving it.
I have added a line chart onto a modal box. The chart displays, but only at half the height of the modal height, when I would have expected the entire modal height to be used.
My HTML code is follows
<div id = "myModal" class="modal">
<div class="modalContent">
<span class = "close"> </span>
<div id="data_chart"></div>
</div>
</div>
The jquery function I use to create the chart is below, I left out some formatting codes for simplicity.
function renderChart() {
//===========================
var len = data_obj["trend"]["x"].length;
var trend_data = []
for (var i=0; i<len; i++){
var d = new Date(data_obj["trend"]["x"][i]);
var t = {"date": d, "value": data_obj["trend"]["y"][i]};
trend_data.push(t)};
var chart = am4core.create("data_chart", am4charts.XYChart);
chart.data=trend_data;
var title = chart.titles.create();
title.text = "Pulse Index";
title.marginBottom = 30;
title.fontSize = 16;
var dateAxis_line = chart.xAxes.push(new am4charts.DateAxis());
dateAxis_line.renderer.inside = true;
dateAxis_line.renderer.grid.template.disabled = true;
// Create value axis
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
};
The output of the modal & chart shows the chart's height is not fully occupying the height of the modal box. I am not sure why.
For more detail, the DOM details are
Many thanks!

How to set the position of the progress bar?

I have an audio player on a page. I have a custom progress bar that I created. When users click on that progress bar, I want to tell the audio player to start playing at that position. How do I detect the position of where the person clicked in the div and translate that to a position to play the song?
var aud = $('audio')[0];
var index = 0;
$('.play').on('click', function() {
aud.src = $(this).attr('data-url');
index = $(this).index('.play');
if (aud.paused) {
aud.play();
} else {
aud.pause();
}
});
aud.ontimeupdate = function() {
$('.progress-bar-wrapper').hide();
$('.progress-bar-wrapper:eq(' + index + ')').show();
$('.progress:eq(' + index + ')').css('width', aud.currentTime / aud.duration * 100 + '%')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio src="" style="display: none"></audio>
<div class="play" data-url="{{url}}"><img src="/images/play_course.png" /></div>
<div class="progress-bar-wrapper">
<div class="progress"></div>
</div>
You can get the position of the mouse inside the click event.
I have added two variables inside the click event with both the position of the mouse relative to the element itself and the percentage that the click position represent, use them as you see fit.
Note: I added width and height for the progress bar so I can test your code so keep in mind that the progress wrapper needs to be visible and have a width value.
var aud = $('audio')[0];
var index = 0;
$('.play').on('click', function() {
aud.src = $(this).attr('data-url');
index = $(this).index('.play');
if (aud.paused) {
aud.play();
} else {
aud.pause();
}
});
$(".progress-bar-wrapper").on("click", function (e) {
var posX = e.pageX - $(this).offset().left;
var percentage = parseInt((posX / $(this).width()) * 100);
});
aud.ontimeupdate = function() {
$('.progress-bar-wrapper').hide();
$('.progress-bar-wrapper:eq(' + index + ')').show();
$('.progress:eq(' + index + ')').css('width', aud.currentTime / aud.duration * 100 + '%')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio src="" style="display: none"></audio>
<div class="play" data-url="{{url}}"><img src="https://cdn.iconscout.com/icon/premium/png-512-thumb/play-button-1516951-1285078.png" /></div>
<div class="progress-bar-wrapper">
<div class="progress"></div>
</div>

Change background colour (scrolling) when an element comes to a certain point (Responsive)

Sorry guys, I am very new to Javascript. I have searched for similar solutions before posting here.
I want to change the background colour, every time that multiple div tags, with specific ids, come 150 pixels before they reach the browser top. I want it to work in different devices correctly. I tried different things in javascript but none gave me the responsiveness I want. When I reduce the browser's width, the text is folding and the div/ids positions change. So, my logic is... if, for example, a div with id="One" is 150px from top, change the background colour.
var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
window.addEventListener('scroll', () => {
if(one.getBoundingClientRect().top < 150){
document.body.addClass = "bg-one";
}
});
.site-main{
background-color: white;
}
.bg-one{
background-color: red;
}
.bg-two{
background-color: blue;
}
.bg-three{
background-color: yellow;
}
<body class="site-main" id="main">
<div id="one" class="">Text</div>
<div id="two" class="">Text</div>
<div id="three" class="">Text</div
</body>
I was thinking about that, but it doesn't work.
My solution would be to add an event listener on window scroll
window.onscroll = function(){ft_onscroll()};
in this function, you get the current scroll position. Compare it to your element position to do what you want.
one_y = one.getBoundingClientRect().top;
function ft_onscroll(){
y = window.scrollY;
if(one_y > y){
//change background color
}
}
I made it. My final code is this. Maybe I will make it shorter.
window.onscroll = function(){
fromTop_onscroll();
};
function fromTop_onscroll(){
var main = document.getElementById("main");
var one = document.getElementById("one");
one_distance = one.getBoundingClientRect().top; // distance from top
var two = document.getElementById("two");
two_distance = two.getBoundingClientRect().top; // distance from top
if(one_distance < 150 && two_distance > 150){
main.classList.add("bg-one");
main.classList.remove("site-main");
main.classList.remove("bg-two");
} else if (two_distance < 150 && one_distance < 0) {
main.classList.add("bg-two");
main.classList.remove("bg-one");
} else if (one_distance > 150 && two_distance > 150){
main.classList.add("site-main");
main.classList.remove("bg-two");
main.classList.remove("bg-one");
}
}

Different Images Based On A Range Of Score

I recently was following a youtube tutorial on creating a whack-a-mole type game: https://www.youtube.com/watch?v=toNFfAaWghU.
I followed the code just fine till the end and now I'm wondering if it is possible to set up a system that could detect the score of the user when the time runs out and show different pictures (1-5 star ratings) based a range of scores.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Whack-A-Bear!</title>
<link href='https://fonts.googleapis.com/css?family=Amatic+SC:400,700' rel='stylesheet' type='text/css'>
<link href='https://www.cssfontstack.com/Gill-Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<audio autoplay>
<source src="Outrun - Original Arcade Music.mp3" type="audio/mpeg">
</audio>
<h1>Whack-A-Bear! <span class="score">0</span></h1>
<center><h2>But Not A Hare!!</h2></center>
<div id="timer">
<h2>Timer</h2>
<p id="TimerDisplay">00:15</p>
</div>
<center><button onClick="startGame()">Click Here To Start!</button></center>
<div class="game">
<div class="hole hole1">
<div class="mole"></div>
</div>
<div class="hole hole2">
<div class="mole"></div>
</div>
<div class="hole hole3">
<div class="mole"></div>
</div>
<div class="hole hole4">
<div class="mole"></div>
</div>
<div class="hole hole5">
<div class="mole"></div>
</div>
<div class="hole hole6">
<div class="mole"></div>
</div>
</div>
<script>
/*https://medium.freecodecamp.org/javascripts-var-let-and-const-variables-explained-with-a-story-2038e3c6b2f9 */
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
/*The querySelector() method only returns the first element that matches the specified CSS selectors.
To return all the matches, use the querySelectorAll() method instead.*/
let lastHole;
let timeUp = false;
let score = 0;
//set random timing for the moles to pop up
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
//set random holes for the moles to pop up from the list of our six holes
function randomHole(holes) {
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
// if by chance, we keep getting the same one as the last one, run the function again
if (hole === lastHole) {
//shows that it was about to show you the same hole but didn't so ran the function again
console.log('Ah nah thats the same one bud');
return randomHole(holes);
}
lastHole = hole;
return hole;
}
function peep() {
var imgs = ["yes.png", "Final Hare.png"];
var i = Math.floor(Math.random() * imgs.length);
var raccoon = document.getElementById('raccoon.png');
// these random times refer to how long the mole will stay popped up
const time = randomTime(200, 1000);
const hole = randomHole(holes);
//shows the random home in a random amount of time
console.log(time, hole);
var mole = hole.querySelector(".mole");
mole.style.background = "url('" + imgs[i] + "') bottom center no-repeat";
mole.style.backgroundSize = "60%";
//triggers the CSS to get the mole to come up
hole.classList.add('up');
//makes the mole go away after it has come up => means after the time's up, remove the mole
setTimeout(() => {
hole.classList.remove('up');
//if the time is not up, then run peep () again
if (!timeUp) peep();
}, time);
}
function startGame() {
scoreBoard.textContent = 0;
timeUp = false;
score = 0;
peep();
//a Timeout function will run when time up is true at 10 seconds
setTimeout(() => timeUp = true, 15000)
var sec = 15;
var timer = setInterval(function(){
document.getElementById('TimerDisplay').innerHTML='00:'+sec;
sec--;
if (sec < 0) {
clearInterval(timer);
}
}, 1000);
}
function bonk(e) {
//function bonk will take in an event which will be us clicking each of the moles
//you can simulate a click in JS but here we don't want that to be possible
if(!e.isTrusted) return; // cheater! To prevent a fake click if the event is not trusted, not clicked with mouse
score++;
this.parentNode.classList.remove('up');
scoreBoard.textContent = score;
}
moles.forEach(mole => mole.addEventListener('click', bonk));
</script>
</body>
</html>
Use a switch statement for the image on the end screen such as
switch(true){
case score > firstStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE1.png\")";
break;
case score > secondStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE2.png\")";
break;
case score > thirdStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE3.png\")";
break;
case score > fourthStarRatingValue:
document.getElementById("END IMAGE ID").style.backgroundImage = "url(\"IMAGE4.png\")";
break;
default:
//because you probably don't want an upper limit on score
document.getElementById("END IMAGE ID").style.backgroundImage = "IMAGE5.png";
}
And you would call that at the end
and because I didn't know the id for the end, i just put END IMAGE ID so that is something you'll have to change.
In the future, please cut your code down to a minimal example. It makes things easier to read for the ones trying to help.

Add image as an attribute value in popover(solved)

I am trying to show an image in the popover,
after i created an element i add attributes to show an popover.
var item = document.createElement('div');
var att2 = document.createAttribute("data-toggle");
var att3 = document.createAttribute("title");
var att4 = document.createAttribute("data-content");
var att5 = document.createAttribute("data-placement");
att4.value = "<img src ='blablabla.png' />;"
att3.value = itemname;
att2.value = "popover";
att5.value = "top"
item.setAttributeNode(att5);
item.setAttributeNode(att2);
item.setAttributeNode(att3);
item.setAttributeNode(att4);
any idea ? the output in the popover content is <img src ='blablabla.png' />;
SOLUTION
just add html:true into
$('[data-toggle="popover"]').popover({html:true,trigger:"hover",container: 'body'});
function addImg(theDiv,theImg) {
var element = document.createElement("img");
element.src = theImg;
document.getElementById(theDiv).appendChild(element);
}
<div id="myDiv" onclick="addImg('myDiv','https://media1.popsugar-assets.com/files/thumbor/7NnYpYvDfxr_HYUpa4tySashCM8/fit-in/1024x1024/filters:format_auto-!!-:strip_icc-!!-/2017/03/17/915/n/1922398/40d6ad1840bc51bf_GettyImages-89938282/i/1997.jpg')">
Click me to append image
</div>
Is this kinda what you're after? Hard to tell from your explanation.