I'm working on a project I inherited involving JS which I'm new to. I need to change the z-index of markers on a map and a few other objects on the page.
Is there a way to set the z-index for all my features (to 7) when they are imported? I tried z-index: 7; in .setHTML. Any other suggestions?
geojson.features.forEach(function(feature) {
let type = feature.properties['type'];
let symbol = icons[type];
// create class names to use as tags for filtering
let typeTag = typeTags[type];
let title = feature.properties['title'];
let impact = feature.properties['impact'];
let impactTag = impactTags[impact];
let sType = feature.properties['studyType'];
let studyType = studyTypes[sType];
let tooltipStudy = feature.properties['studyType'];
let ttStudy = tooltipStudyTypes[tooltipStudy];
let uniqueStudies = feature.properties['unique'];
let uniqueStudy = unique[uniqueStudies]
// replave hash marks with smart quotes
let summary = feature.properties['summary'];
summary = "\u201c" + summary + "\u201d";
let url = feature.properties['link'];
let citation1 = feature.properties['citation'];
let clipCitation = citation1.split("),")[0];
console.log(clipCitation)
let substr = "pdf";
if (url.indexOf(substr) !== -1) {
clipCitation = clipCitation + " [pdf]";
}
// create a HTML element for each feature
var el = document.createElement('div');
el.className = "marker" + " " + typeTag + " " + impactTag;
el.innerHTML = '<i class="' + symbol + '"></i>';
// make a marker for each feature and add to the map
new mapboxgl.Marker(el)
.setLngLat(feature.geometry.coordinates)
.setPopup(new mapboxgl.Popup({ offset: 10, closeButton: false }) // add popups
.setHTML('<h4 style="padding-bottom: 4px; border-bottom: 2px solid ' + colors[impactTag] + ';">' + feature.properties['title'] + '</h4><ul class="list-group list-tooltip"><li>Area of study: ' + feature.properties['location'] + '</li><li><div style="display:inline-block" class=' + impactTag + '>' + popupIcon[type] + "</div>"
+ impactTag + " " + 'that climate change increases the risk of wildfires.</li></ul><p class="summary">'
+ summary + '</p><p class="citation"><a href="'
+ url + '" target="_blank">' + clipCitation + "),</a><span class='citation2'> " + feature.properties['journal'] + '</span></p>'))
.addTo(map);
});
To change any CSS styles with JavaScript use document.getElementById("item").style.XXX = "value";, change XXX with the thing you want to change, in your case z-index:
document.getElementById("item").style.zIndex = "7";
you can do the same thing with jQuery with more simple way :
$("#item").css("z-index","7");
Related
The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1
Im trying to change the cursor logo when Im building a dynamic div. Depending on how much data it can take up a few seconds to load so I need the cursor change.
The problem Im having is that the cursor isnt changing until my code has fully executed.
Im have a dynamically generated chart with the points in the chart set to popup more data when they are clicked. This is the eventListener Ive created and it works fine apart from my CSS update not getting applied until it has exited the function.
Any idea how I can force it to update immediately
point.addEventListener('click', function (evt) {
document.body.className = 'waiting';
var evtPoint = document.getElementById(evt.currentTarget.id);
var index = evtPoint.id.substring(evtPoint.id.lastIndexOf('-') + 1, evtPoint.id.length);
var chartOptions = Charts.options[elementId];
var txnData = chartOptions.data.txn[index];
var txnFullData = chartOptions.data.txnFull;
var theDate = new Date(txnData.time);
// pop up
var txnsPerMinutePopUp = document.getElementById('txnsPerMinutePopUp');
txnsPerMinutePopUp.innerHTML = '<div id = "txnsPerMinutePopUp-bg"></div>' +
'<div id = "txnsPerMinutePopUp-body">' +
'<div id = "txnsPerMinutePopUp-body-heading"></div>' +
'<div id = "txnsPerMinutePopUp-body-txns">';
var txnsPerMinutePopUpHeading = document.getElementById('txnsPerMinutePopUp-body-heading');
var txnsPerMinutePopUpBody = document.getElementById('txnsPerMinutePopUp-body-txns');
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
for (var i = 0; i < txnFullData.length; i++) {
// console.log("loop" + i, txnFullData);
var date = new Date(txnFullData[i].time);
if (date.getTime() === theDate.getTime()) {
txnsPerMinutePopUpHeading.innerHTML = '<div class="txnsPerMinutePopUp-body-heading-title">Tweets</div><div class="txnsPerMinutePopUp-body-heading-time">' + addZero(theDate.getHours()) + ':' + addZero(theDate.getMinutes()) + '</div>';
var child = '<div class = "txnsPerMinutePopUp-txns">' +
'<div class = "txnsPerMinutePopUp-txns-img">' +
'<object data = "' + txnFullData[i].profile_image_url + '" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" type = "image/jpeg">' +
'<img src = "assets/img/engager_profile_default-47.svg" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" alt = "' + txnFullData[i].screen_name + ' profile image" />' +
'</object>' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-screen-name">' +
'#' + txnFullData[i].screen_name + '' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-text">' + Charts.lineChart.parseText(txnFullData[i].text) + '</div>' +
'</div>';
txnsPerMinutePopUpBody.innerHTML += child;
}
}
txnsPerMinutePopUp.innerHTML += '</div>' +
'</div>';
//document.body.style.cursor='default';
txnsPerMinutePopUp.style.visibility = 'visible';
var bg = document.getElementById('txnsPerMinutePopUp-bg');
bg.addEventListener('click', function (evt) {
txnsPerMinutePopUp.style.visibility = 'hidden';
});
}, false);
My CSS then is just
body.waiting * { cursor: wait; }
UPDATE
From researching potential causes I found out that most browsers wont update the DOM immediately and I need to interrupt the javascript to allow for the DOM to get updated.
Ive updated my code to move the bulk of the operations out to a separate function and tried to set a timeout value on it and its still not updating the cursor until everything completes.
I also tried to add a mousedown event to try and get ahead of the javascript in the on click but it didnt work either
EventListener
point.addEventListener('click', function (evt) {
//document.body.className = 'waiting';
// setTimeout(function() {
Charts.lineChart.changeCursor();
// },10);
var evtPoint = document.getElementById(evt.currentTarget.id);
var index = evtPoint.id.substring(evtPoint.id.lastIndexOf('-') + 1, evtPoint.id.length);
var chartOptions = Charts.options[elementId];
var txnData = chartOptions.data.txn[index];
var txnFullData = chartOptions.data.txnFull;
var theDate = new Date(txnData.time);
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
setTimeout(function() {
Charts.lineChart.breakOut( txnFullData,theDate );
},100);
document.body.style.cursor='default';
txnsPerMinuteTweetsPopUp.style.visibility = 'visible';
}, false);
and the following code was moved into the breakout function
breakOut
Charts.lineChart.breakOut = function(txnFullData,theDate){
function addZero(i) {
if (i < 10) {
i = '0' + i;
}
return i;
}
var txnsPerMinutePopUp = document.getElementById('txnsPerMinutePopUp');
txnsPerMinutePopUp.innerHTML = '<div id = "txnsPerMinutePopUp-bg"></div>' +
'<div id = "txnsPerMinutePopUp-body">' +
'<div id = "txnsPerMinutePopUp-body-heading"></div>' +
'<div id = "txnsPerMinutePopUp-body-txns">';
var txnsPerMinutePopUpHeading = document.getElementById('txnsPerMinutePopUp-body-heading');
var txnsPerMinutePopUpBody = document.getElementById('txnsPerMinutePopUp-body-txns');
for (var i = 0; i < txnFullData.length; i++) {
// console.log("loop" + i, txnFullData);
var date = new Date(txnFullData[i].time);
if (date.getTime() === theDate.getTime()) {
txnsPerMinutePopUpHeading.innerHTML = '<div class="txnsPerMinutePopUp-body-heading-title">Tweets</div><div class="txnsPerMinutePopUp-body-heading-time">' + addZero(theDate.getHours()) + ':' + addZero(theDate.getMinutes()) + '</div>';
var child = '<div class = "txnsPerMinutePopUp-txns">' +
'<div class = "txnsPerMinutePopUp-txns-img">' +
'<object data = "' + txnFullData[i].profile_image_url + '" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" type = "image/jpeg">' +
'<img src = "assets/img/engager_profile_default-47.svg" class = "border-rad-25 cross-series-profile-img" width = "50px" height = "50px" alt = "' + txnFullData[i].screen_name + ' profile image" />' +
'</object>' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-screen-name">' +
'#' + txnFullData[i].screen_name + '' +
'</div>' +
'<div class = "txnsPerMinutePopUp-txns-text">' + Charts.lineChart.parseText(txnFullData[i].text) + '</div>' +
'</div>';
txnsPerMinutePopUpBody.innerHTML += child;
}
}
txnsPerMinutePopUp.innerHTML += '</div>' +
'</div>';
var bg = document.getElementById('txnsPerMinutePopUp-bg');
bg.addEventListener('click', function (evt) {
txnsPerMinutePopUp.style.visibility = 'hidden';
});
}
Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});
I'm working on a simple aplication based on localStorage and I have a problem with removing an item.
So, I'm adding new items to LS and display them as divs in for loop.
I created an easy "X" button on every card and here is a thing. How can I get an ID/position of this specific card after clicking "X" and pass it to remove function?
I'll present you my code:
// Display activities
var fetchActivities = function() {
var activities = JSON.parse(localStorage.getItem("activitie"));
const actCountContainer = document.getElementById("actCountContainer");
actCountContainer.innerHTML = "";
actCountContainer.innerHTML += "<div class='col-md-12'>" +
"<p>Your activities ("+activities.length+")";
var actCardContainer = document.getElementById("actCardContainer");
actCardContainer.innerHTML = "";
for (let i = 0; i < activities.length; i++) {
actCardContainer.innerHTML += '<div class="col-md-4">'+
'<div class="card">' +
'<div class="card-block">' +
'<div id="remove" class="remove">X</div>' +
'<h4 class="card-title">'+ activities[i].name + '</h4>' +
'<ul class="card-text">' +
'<li>Total time spent: 2h 25min 34sec</li>' +
'</ul>' +
'Go to this activity' +
'</div>' +
'</div>' +
'</div>'
}
const removeButton = document.getElementById("remove");
if (removeButton) {
removeButton.addEventListener("click", removeActivity);
};
};
// Add activity function
var addActivity = function() {
const actInput = document.getElementById("activityInput").value;
// Main activity object
var activity = {
name: actInput
};
if (localStorage.getItem("activitie") == null) {
var activities = [];
activities.push(activity);
localStorage.setItem("activitie", JSON.stringify(activities));
} else {
var activities = JSON.parse(localStorage.getItem("activitie"));
activities.push(activity);
localStorage.setItem("activitie", JSON.stringify(activities));
}
fetchActivities();
};
// Remove activity function
var removeActivity = function() {
};
const addButton = document.getElementById("addBtn");
addButton.addEventListener("click", addActivity);
I'd be very grateful if you can give me an idea how can I handle this remove function.
I would rewrite fetchActivities as follows
var fetchActivities = function() {
var activities = JSON.parse(localStorage.getItem("activitie"));
const actCountContainer = document.getElementById("actCountContainer");
actCountContainer.innerHTML = "";
actCountContainer.innerHTML += "<div class='col-md-12'>" +
"<p>Your activities ("+activities.length+")";
const actCardContainer = document.getElementById("actCardContainer");
actCardContainer.innerHTML = "";
let items = "";
for (let i = 0; i < activities.length; i++) {
itemsHTML += '<div class="col-md-4">'+
'<div class="card" data-id="' + activities[i].id + '">' +
'<div class="card-block">' +
'<div class="remove" data-id="' + activities[i].id + '">X</div>' +
'<h4 class="card-title">'+ activities[i].name + '</h4>' +
'<ul class="card-text">' +
'<li>Total time spent: 2h 25min 34sec</li>' +
'</ul>' +
'Go to this activity' +
'</div>' +
'</div>' +
'</div>'
}
actCardContainer.innerHTML = items;
// ... for attach event read on
};
Notes:
Do not set the same id if an element appears many times
Set innerHTML once not for each loop iteration
Set unique id for every item (you could generate random numbers for example)
To attach events you would need to do it as follows (taken from question ):
var removeLink = document.querySelectorAll('.remove');
Then you would loop:
for (var i = 0; i < deleteLink.length; i++) {
removeLink[i].addEventListener('click', function(event) {
var acrtivityId = event.currentTarget.getAttribute('data-id');
removeActivity(acrtivityId);
// Use
});
}
Now for the removal you can find current activity in the activity array and remove it. Use find and then splice for example. And save the change array to local storage. On creation assign an id.
The table cell updates correctly to "" (empty) in the changeScore function, but that same cell does not change at all in the editUpdate function when I try to place the new score in there. It just stays empty. Any ideas?
function changeScore(playerKey)
{
var table = document.getElementById("scoreTable");
players[playerKey].score = players[playerKey].oldScore;
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
document.getElementById('inputArea').innerHTML = '<font size="6">Did <b>' + players[playerKey].name + '</b> take <b>' + players[playerKey].bid + '</b> trick(s)?</font><br /><button value="Yes" id="yesButton" onclick="editUpdate(' + playerKey + ', \'yes\')">Yes</button>    <button value="No" id="noButton" onclick="editUpdate(' + playerKey + ', \'no\')">No</button>';
}
function editUpdate(thePlayerKey, answer)
{
var table = document.getElementById("scoreTable");
players[thePlayerKey].oldScore = players[thePlayerKey].score;
if (answer == "yes"){
**
}else{
**
}
table.rows[currentRound - 1].cells[thePlayerKey + 1].innerHTM = '<font color="' + players[thePlayerKey].font + '">' + players[thePlayerKey].score + '</font>';
document.getElementById('inputArea').innerHTML = '<button onclick="startRound()">Start Round</button>     <button onclick="edit()">Edit Scores</button>';
}
innerHTM should be innerHTML
This:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
Should be:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTML = '';
(Same for 2nd function)