How to reveal dynamic data on click with jquery - javascript

EDIT: This is a more sound approach, since provided answer may have bugs when implementing a tags, or img tags.
================================================================
I am calling blog data from an API. (I've reformatted the data into an array by month).
So far, the blog titles print to the web page. I'd like a user to be able to click a title and have its description revealed.
Here is some of my code so far:
var blogPosts = $('#blog-posts');
$.each(byMonth, function(key, value) {
var outer = byMonth[key]
$.each(outer, function(k, v) {
var inner = outer[k]
var monthBlogPosts = $('<div class = "month"> </div>').appendTo(blogPosts);
$.each(inner, function(i, obj) {
title = inner[i].Title
description = inner[i].Description
date = inner[i].DatePublished
$('<div class = "title-list"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
// if a title is clicked, show its Description
showDescription(description);
})
})
});
function showDescription(d){
$('.unique-title').on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
When I click a title, all descriptions print instead of the matching description. I understand this is because I called the function in a nested loop, but I've also had trouble calling the description variable outside of it.
I have also tried
showDescription(title, description)
//...
function showDescription(t, d){
$(title).on('click', function(){
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})
}
but then nothing is printed to the html page.
Essentially, I'd like to grab the title index, and print it's respective description when its clicked.

you should use event delegation to attach a click event to the document that will bubble up and trigger when .title-list is the event target.
$(document).on('click', '.title-list', function(event) {
showDescription(event.currentTarget) // pass the element being clicked (we will need it later)
})
you would also need to modify the way you get the description.
you could store you description in a data attribute of .title-list like so:
$('<div class = "title-list" data-description="'+ description +'"><h3 class = "unique-title">' + title + '</h3></div>').appendTo(monthBlogPosts)
so you can now modify showDescription() so it would get the data from the element we pass to the function
function showDescription(element){
var d = $(element).data('description')
$('<p>' + d + '</p>').appendTo('body')
console.log(d)
})

So ok. From whatever I could understand (by looking at your code). You cannot register an event with simple on for dynamically added element. You have to use on delegate.
Try this
1) remove the function call (inside a loop)
2) delete the entire function showDescription and add event as below:
$('#blog-posts').on('click', '.unique-title',function(){
alert('title clicked').
});
3) As to display the description I think the best way will be to add the description in a div and hide it. Display it later once the title is clicked.
(inside the loop)
$('<div class = "desc" style="display:none">' + description + '</div>').appendTo(monthBlogPosts);
then on #2 above. Replace with this.
$('#blog-posts').on('click', '.unique-title',function(){
$(this).next('.desc').show(); //I am assuming desc will be next to the clicked title here. You can modify it as needed.
});
Finally, this is just an overview of a code so might not work as expected but I am pretty sure this should give you an idea and get you started

Related

How can make data of each table row into different query string and pass data to another view

As I have made the table body in my javascript which is shown in the below code. As I am new to programming, can anyone tell how to make data of each table row into querystring then pass to another page like html? Thank in advance
var Ref = firebase.database().ref().child("posts");
Ref.on("child_added", snap => {
var name = snap.child("name").val();
var region = snap.child("region").val();
var form = snap.child("form").val();
var code = snap.child("code").val();
$("#table_body").append("<tr><td><a href='postlist.html?key='>" + code + "</td><td>" + name + "</td><td>" + region + "</td><td>" + form. +"</a></td><td>");
$("#table_body").off("click").on( "click", "tr", function() {
});
I would use an HTML5 data attribute on each row to associate the table row with a record held in a persistent array. The click handler would read the data-attribute, pull the target row from the array in order to construct the URL.
So...
const posts = []
const Ref = firebase.database().ref().child("posts")
Ref.on("child_added", snap => {
posts.push({
'name': snap.child("name").val(),
'region': snap.child("region").val(),
'form': snap.child("form").val(),
'code': snap.child("code").val()
})
})
Then, use that array to generate the table:
posts.forEach((post, i) => {
$("#table_body")
.append(`
<tr data-post-index="${i}">
<td>${post.code}</td>
<td>${post.name}</td>
<td>${post.region}</td>
<td>${post.form}</td>
</tr>
`);
})
I removed an <A> tag that was being used badly. You cannot start an <A> in one table cell and then close it in a different table cell. And, since it seems you want row-clicks to be handled using javascript, that anchor is superfluous.
Finally, let's set up the click handler. It will rely on the fact that each row has an HTML attribute that indicates the index of the full record in the array.
$("#table_body").off("click").on( "click", "tr", function() {
const postIndex = $(this).attr('data-post-index')
const post = posts[postIndex]
window.location = `postlist.html?key=${post.code}` // or whatever
});
Warning: it's been a while since I used jquery. I seem to recall that jquery event handlers receive the clicked element as this. If that's not the case, you might need to do a little more work inside that handler to identify the relevant <TR> from the event.
If that's the case, post a comment and I can dig into it. Or you could do a little research and figure it out yourself.

jQuery remove class item keeps coming back

Here is the situation.
I'm trying to remove an div class item based when the user clicks on a rating.
The problem I have is that every time I click on the item it goes away, however when I move the mouse the item that I removed comes back.
Here is my current code:
<div class="star_'.($iPos+1).' ratings_stars ratings_vote" onmouseover="overRating(this);" onmouseout="outRating(this);" onClick="selectEmailRating(this);" ></div>
The above item is the div that is calling the JavaScript. When I click on the rating I run the code that is in the following function below:
function selectEmailRating(elem) {
var star = elem;
var rating = widget.data('fsr').rating;
if($(star).attr('class') === 'star_'+ rating + ' ratings_stars ratings_over ratings_vote'){
$(elem).andSelf().removeClass();
$(star).attr('class', 'star_'+ rating + ' ratings_stars');
$(star).attr('class').unbind('onmouseover').unbind('onmouseout');
}
function outRating(elem) {
$(elem).prevAll().andSelf().removeClass('ratings_over');
setRating($(elem).parent());
}
function overRating(elem) {
$(elem).prevAll().andSelf().addClass('ratings_over');
$(elem).nextAll().removeClass('ratings_vote');
}
function setRating(widget) {
var votes = $(widget).data('fsr').rating;
$(widget).find('.star_' + votes).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + votes).nextAll().removeClass('ratings_vote');
}
As you see in the code, it is removing the item, however, it is coming back when I move the mouse. Is there a way to make sure when I click on the item to remove it stays removed?
I may be wrong here, but you didn't "bind" the onmouse* events to the element, you added attributes.
You may overwrite the onmouse* attributes with $(elemment).attr('onmouseout', '') or something alike.
and you might want to have a look at https://api.jquery.com/hasclass/
Well I found a solution..
After trying to figure out why the rating keeps coming back, it was the due to the fact that the outRating function was causing the problem. Here is what I did...
The old outRating function:
function outRating(elem) {
$(elem).prevAll().andSelf().removeClass('ratings_over');
setRating($(elem).parent());
}
The new outRating function:
function outRating(elem) {
var star = elem;
var widget = $(elem).parent();
var rating = widget.data('fsr').rating;
$(elem).prevAll().andSelf().removeClass('ratings_over');
if($(star).attr('class') !== 'star_'+ rating + ' ratings_stars') {
setRating($(elem).parent());
}
}

Adding and removing a class at the same time as updating a div

I am very new to JavaScript. I am trying to update a div, which works fine before the add and remove class pieces are added. The problem is when I add the class I can't seem to get it to be removed when the when the next image is clicked. I have used a remove class option, but it doesn't seem to want to work.
Any help is appreciated. Here is the code:
$('[class^="question"]').on('click', function(e) {
e.preventDefault();
var numb = this.className.replace('question', '');
$('[id^="answer"]').hide();
$('.question*').removeClass('question*selected');
$('#answer' + numb).show();
$('.question' + numb).addClass('question' + numb + 'selected');
});
Here is a link to the Fiddle I am Playing with.
Thanks.
You can keep track of your added class by defining a global variable. I created a working example in CODEPEN.
$(document).ready(function() {
var appliedClass = "container1";
var classNo = 1;
$(".buttonCon").click(function() {
if ($(".container").hasClass(appliedClass)) {
$(".container").removeClass(appliedClass);
classNo++;
if (classNo > 4) {classNo = 1;}
appliedClass = "container" + classNo;
$(".container").addClass(appliedClass);
}
});
});
I have appliedClass variable which keeps tracking of the latest added class. Every time you click on the button with .buttonCon class, this variable will be updated to the new added class. Next time, first we remove the former class. Then we added the new one. The second if statement might not be needed in your case, but in my example, I needed it to keep looping through container1 to container4 classes.
You've set yourself up with a really difficult-to-work-with class structure -- this can be a lot easier than you're making it. Give each of your "question" links the class 'question' and the unique id "question1", "question2", etc. Same for the answer nodes: class "answer" and id "answer1", "answer2" etc.
Now you can easily access all question links with $('.question') or all answers with $('.answer'), and can use the IDs to identify individual nodes as needed:
$('.question').on('click', function(e) {
e.preventDefault();
var numb = this.id.replace('question', '');
var answerNode = $('#answer'+numb);
if (answerNode.hasClass('hide')) {
// the Q they clicked on is not yet visible
$('.answer').addClass('hide'); // hide all answers
answerNode.removeClass('hide'); // show the desired one
} else {
// the Q they clicked on is already visible, so toggle it back off
answerNode.addClass('hide');
}
});
http://jsfiddle.net/647dadtj/

JQuery get calling <script> tag when dynamically loaded

How can I locate the tag which calls a JQuery script, when
the tag is dynamically loaded, so won't be the last
tag on the page?
I'm using the MagicSuggest autosuggest library. I want to give certain suggested items a different background color depending on their contents, which I'm currently doing by adding JQuery inside a tag, which I'm adding on to the String which is returned to be rendered inside the selection div. Then, to get the div the item is suggested in, I need to essentially get the parent() of the tag, and change it's css() properties. How can I get this current script tag however?
I'm currently assigned each new tag an id generated from incrementing a JS variable - which works, but isn't very 'nice'! Is there anyway I can directly target the tag with JQuery?
If it perhaps makes it clearer, here is my current selectionRenderer function.
selectionRenderer: function(a){
var toRet = a.english;
var blueBgScript = "<script id=ft" + freeTextFieldID + ">$('#ft" + freeTextFieldID + "').parent().css('background', 'blue');</script>"
if(a.id==a.english){
toRet += blueBgScript;
freeTextFieldID++;
}
return toRet;
},
Why don't you add some code at afterrender event instead? Add some tag to flag the options that need a different background, then detect the parents and add a class (or edit the bg property) or whatever you like:
var newMS = $('#idStr').magicSuggest({
data: 'states.php',
displayField: 'english',
valueField: 'id',
selectionRenderer: function(a){
var toRet = a.english;
if(a.id==a.english) toRet = "<span class='freetext'>" + toRet + "</span>";
return toRet;
},
});
$(newMS).on('selectionchange', function(event,combo,selection){
var selDivs = $(event.target._valueContainer[0].parentNode).children('div'); //Get all the divs in the selction
$.each(selDivs,function(index,value){ //For each selected item
var span = $(value).children('.freetext'); //It if contains a span of class freetext
if(span.length == 1) $(value).css('background','blue'); //Turn the background blue
});

JS: Click one div, change another div value

I have a vote button I created that is contained within a .vote_div. 2 parts: .vote_num for the vote total, and .vote for the vote button. The page has a list of items so I need to make sure when the user clicks .vote, it changes the corresponding .vote_num + 1.
My JS function worked when the .vote actually was the total votes, but now I am seperating the two. How do I grab the right .vote_num on the .vote click?
Thanks!
<script>
$(".vote").click( function() {
var votes = $(this).attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
$(this).text(parseInt(votes) + 1);
return false;
});
</script>
<div class="vote_div">
<span class="vote_num" votes='{{host.num_votes}}'>{{host.num_votes}}</span>
<span class="vote" id="{{host.user.id}}">Vote</span>
</div>
EDIT & SOLUTION:
Got it working using $(this).parent() :
<script>
$(".vote").click( function() {
var votes = $(this).parent().find('.vote_num').attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
votes = parseInt(votes) + 1;
$(this).parent().find('.vote_num').text(votes);
return false;
});
</script>
try:
var votes = $(this).parent().find('.vote_num').attr('votes');
It goes to the parent of the clicked div then looks for an element with class vote_num then grabs the votes attributes.
#James answer should work, but this should give you a little more freedom to rearrange the two divs and add other elements so long as they share the parent.
To be even more robust you could do (note the 's' on "parents")
var votes = $(this).parents('.vote_div').find('.vote_num').attr('votes');
This will allow the elements to be nested arbitrarily deep as long as they only have a single parent with a class of `vote_div'.
See: http://api.jquery.com/parent/ , http://api.jquery.com/parents/ , and http://api.jquery.com/find/
if you have multiple class with vote, maybe you should use each()
$(".vote").each(function () {
var current = $(this);
current.click = function () {
// the rest of your function
}
})
Assuming I've understood the question correctly, and also assuming that your vote_num element is always the first element in the vote_div element:
var votes = $(this).siblings().eq(0).attr("votes");
Put this inside your click event handler will get the votes attribute from the first sibling element of the clicked element.
You can make this simpler if you are sure the element in question will always be directly before the clicked element:
var votes = $(this).prev().attr("votes");
var votes = $(this).attr('votes');
'votes' does not belong to class 'vote', it belongs to class 'vote_num'
so the line should be
var votes = $(".vote_num").attr('votes');
$('.vote').click(function(){
var $vote_num_obj = $(this).parent().find('.vote_num');
var new_vote_num = parseInt($vote_num_obj.attr('votes'))+1;
$vote_num_obj.attr('votes', new_vote_num);
$vote_num_obj.html(new_vote_num);
});
Put this script inside $('document').ready(function(){ ..here.. });
I suggest to change votes attribute of your span.vote_num to data-votes and change also the jquery attribute selector, this way it will be standard compliant.

Categories