$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>
Related
When a new button is created it isn't being picked up by the rest of the code
var topics = ["dog", "cat", "pangolin", "snake", "bird", "emu", "cow", "hedgehog"]
$(document).ready(function () {
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
});
$("button").click(function() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function(response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
});
});
What I'm trying to do is when the user creates a new button, that button will then work like the premade buttons. The premade buttons are supposed to display a few gifs.
What is happening is that after I create the new button, clicking on that button won't even console log the id of that new button.
Your event listener $("#btnAddSubmit").click worked only with already created buttons. That is means your new buttons will be without this listener. If you want to add listeners to the new buttons, you must do something like:
// We are create event listener as a function for convenient use
var onButtonClick = function () {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
// Your code here...
}
}
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// We are remove all button's listeners and at once add new
$("button").off('click').on('click', onButtonClick);
});
// And this code will add your listener as it was originally
$("button").off('click').on('click', onButtonClick);
Be cearful if your buttons have another event listeners. If it exists, you connot use .off(). In that case is correct way will be add listener for a new specific button's id.
Based on your question and the js code provided, i guess this is because the newly added button doesn't get the event.
All events are attached to the dom on page load. The new buttons that are injected to the DOM doesn't get the events. jQuery already did the bindings to DOM elements before the new code was injected. To solve this you have to use '.on() method in jQuery
Something like this
$(document).on('click','your_button_class_here',function(){
dosomething();
});
You're using the ready callback, so all of this runs when the DOM is ready. However, you don't actually create the new button until this ready callback has already run! So when you try to add callbacks with $("button").click(function(){}), you are trying to add that callback to all the buttons on the DOM... but some of the buttons you want to add it to do not exist yet. They won't exists until that first button's click callback is executed! So the first button you make will have the callback attached, but the new ones will not.
Maybe try something like this? I expect something will be wrong with how the value of this works on your click callback, but I think it's a nudge in the right direction.
$(document).ready(function () {
$("#btnAddSubmit").click(function () {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// be wary of what the value of `this` refers to! it might refer to
// the `this` of the scope in which it was defined!
function gifCallback() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function (response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
};
// reference the new button by its ID and add your desired callback
$("#gif").click(gifCallback)
});
});
I have looked at other Questions of this type and none of them solved my problem. I am having this JavaScript code:
var count1;
for (count1 = 1; count1 < 11; count1++) {
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3 <p>' + article.description + '<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#" + count1).css('background-image', 'url(' + ImageURL + ')');
x = article.url;
}
function divLoad() {
alert(article.url);
};
Basically there are 10 items with different articles. Scopes of variables are all correct. I can see the links of the items when I console log them in the loop. I want to alert each URL whenever each Item is clicked for a respected button. But when I click that I get the error:
Uncaught ReferenceError: divLoad is not defined
at HTMLButtonElement.onclick
Am I missing something?
EDIT [My Full Code]:
var x;
function divLoad() {
alert(x);
};
$(document).ready(function(){
var url = 'https://newsapi.org/v2/top-headlines?country='+country+'&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res){
//console.log(res)
var count1;
for(count1 = 1; count1 < 11; count1++){
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
x = article.url;
$('#showNews').append('<div id="'+count1+'" class="article"><div class="overlayart"><div class="art"><h3>'+article.title+'</h3><p>'+article.description+'<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#"+count1).css('background-image','url(' + ImageURL + ')');
}
});
The problem is that you're always referencing one single, global variable. That variable (x) will only ever hold the last value it was set to in your for loop.
Instead, we can append the articles and give each one a data attribute - that way, we can associate each element with a specific article URL.
function divLoad(url) {
alert(url);
};
$(document).ready(function() {
var url = 'https://newsapi.org/v2/top-headlines?country=' + "test" + '&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res) {
for (let count1 = 1; count1 < 11; count1++) {
let article = res.articles[count1];
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3><p>' + article.description + '<br><br><button class="article-btn">Follow Link</button></p></div></div></div>');
$("#" + count1)
.css("background-image", "url('" + article.urlToImage + "'")
.attr("data-url", article.url); //Associate the URL to the element
}
});
$("#showNews").on("click", ".article-btn", function() {
var url = $(this).closest(".article").attr("data-url"); //Get the associated URL
divLoad(url);
});
});
If you inspect the <div class="article"> now, you'll see each one has a data-url attribute that holds its URL.
i got javaScript array hold elements records with unique elementIndex in it now what I have to add single or multiple components in same javaScript array for that particular element (same elementIdex).
this array can have as many elements as required and each element may have one or multiple components associated to that element.
I have managed to do first part, how i do second part ... that is add components records associated to single element.
note element and component are in separate javaScript function but i have global array
this is what i want to achieve (may be JSON)
QualificationElemenetsAndComponents[0] = {
Element [
ElementIndex : "",
ElementMarkingSchemeTitle : "",
ElementAvailableMark: "",
ElementPassMark: "",
ElementDistinctionMark: "",
Component[0]= [
componentIndex="",
componentMark =""
],
Component[1]= [
componentIndex="",
componentMark =""
],
Component[2]= [
componentIndex="",
componentMark =""
],
}
global array
var selectedComponentList = [];
var selectElementList = [];
element
$("#ElementTable").on("click", ".k1-grid-confirm", function () {
var E_RecordId = $(this).data("id");
var E_MarkingSchemeTitle = $("#" + E_RecordId + "_EMST").val();
var E_AvailableMark = $("#" + E_RecordId + "_AM").val();
var E_PassMark = $("#" + E_RecordId + "_PM").val();
var E_MeritMark = $("#" + E_RecordId + "_MM").val();
var E_DistinctionMark = $("#" + E_RecordId + "_DM").val();
alert("elementRecordId " + E_RecordId + " E_MarkingSchemeTitle " + E_MarkingSchemeTitle + " E_AvailableMark " + E_AvailableMark + " E_PassMark " + E_PassMark + " E_MeritMark " + E_MeritMark + " E_DistinctionMark " + E_DistinctionMark);
//add data to array//
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark });
}
});
Component
$("#ComponentSchemeTable").on("click", ".k-grid-confirm", function () {
var recordId = $(this).data("id");
var ComponentSchemeMark = $("#" + recordId + "_CM").val();
//
$(this).hide();
$(this).siblings(".k-grid-input").hide();
$(this).siblings(".k-grid-cancel").hide();
$(this).siblings(".k-grid-Remove").show();
//add data to array//
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });
//push array to Selected Element
?????????????????????????????????????
}
});
Many thanks
Define a function to refresh the global list:
// Elements
selectElementList.push({...});
refreshGlobalList();
// Components
selectedComponentList.push({...});
refreshGlobalList();
And the function:
var globalList = [];
function refreshGlobalList() {
globalList = selectElementList.concat(selectedComponentList);
}
arrayNum.push.apply(arrayNum, arrayValuTwo);
arrayNum.push.apply(arrayNum, arrayValuThree);
you can try this or you can try this
arrayNumber.push.apply(arrayNumber, arrayValueTwo.concat(arrayValueThree));
Here is a sample of my problem and below is the same code
HTML
<button id='preview_btn'>Add</button>
<table id="point_tbl">
</table>
JavaScript
var pointList = [];
function deletePoint(id) {
console.log(id); // should be string but turns out to be the tr element
for (var i = 0; i < pointList.length; i++) {
if (pointList[i].id == id) {
pointList.splice(i, 1);
document.getElementById(id).remove();
document.getElementById(id + "item").remove();
}
}
}
function getTemplate(obj) {
var id = obj.id + "item";
var aa = obj.id;
var row = "<tr id = '" + id + "'><td>" + obj.sn + "</td><td>" + obj.x + "</td><td>" + obj.y + "</td><td>" + obj.tx + "</td><td>" + obj.ty + "</td><td>" + obj.lbl + "</td><td><button class='del_point' onclick = 'deletePoint("+id+");'>Delete</button></td></tr>";
return row;
}
document.getElementById("preview_btn").onclick = function(event) {
var id = getUniqueId();
var obj = {sn: pointList.length, x: 10, y: 10, tx: "0.5", ty: "0.5", lbl: "", id: id};
$('#point_tbl').append(getTemplate(obj));
pointList.push(obj);
}
function getUniqueId() {
if (!getUniqueId.idList) {
getUniqueId.idList = [];
}
var id = "uniqueID" + Math.round(Math.random() * 1000 + 1);
if (getUniqueId.idList.indexOf(id) != -1) {
return getUniqueId();
} else {
getUniqueId.idList.push(id);
}
return id;
}
When the Add button is clicked a new row is added with a button.
On this newly added button the deletePoint function is bind using the getTemplate function. The deletePoint function accepts the id of the row (tr) created by getTemplate function.
I am logging the the passed parameter in the deletePoint function. I was expecting this to be the id(basically a string) of the row but it turns out to be the whole tr element.
Not able to rectify the problem, please help.
What happens is that the generated code in the event handler is
deletePoint(someId)
instead of being
deletePoint("someId")
As most browsers create a variable in global scope for all elements having an id (the name of the variable being the id), you pass the element, not the string (in some browsers you would pass undefined).
Immediate fix : Change
onclick = 'deletePoint("+id+");'
to
onclick = 'deletePoint(\""+id+"\");'
Better : don't inline JS code in HTML to avoid those problems. For example give an id and data-attribute to your cell and later bind as you do with other elements.
You can change your delete function to fix problem
function deletePoint(id) {
id.remove();
}
I use this jQuery code to append a div to another:
$('#sklep').on('click', '.kup', function () {
var cena = $('#cena').text();
var tytul = $('#tytul').text();
var iden = $('#id').text();
var suma = $('#koszykdiv .cyfry').text();
var dodawanie = parseInt(cena) + parseInt(suma);
$('.cyfry').text(dodawanie);
var source = $("#miniatura").attr("src");
$('.koszyk_content_items').append($('<div class="item_koszyk"><div class="miniatura_koszyk"><img width="165" height="110" src="' + source + '"/></div><span id="opis">' + tytul + ' - ' + cena + ' zł - </span><span class="identyfikator" style="display:none;">' + iden + '</span>USUŃ</div>'));
var licznik = $('#koszykdiv .licznik').text();
alert(licznik);
$('#identyfikator').text(licznik);
var licznik_dodawanie = parseInt(licznik) + 1;
$('#koszykdiv .licznik').text(licznik_dodawanie);
$.cookie("obraz" + licznik_dodawanie, id);
var cena = '';
var tytul = '';
var iden = '';
var source = '';
});
but it always appends a div with the same variables values, even if parent of '.kup' href has another text values. Can you help me and tell where the problem is?
You say in your question that you get the same variable values "even if parent of '.kup' href has another text values."
This is because nothing in your code is relative to the '.kup'-element. You get the src-attribute of the element with id=miniatura everytime.