Struggling to expand div based on dynamic data from database (comments feature) - javascript

I have been struggling with this common social networking feature for quite some time. What I am trying to do is to expand the div to display comments, I'm sure you know what I am talking about.
Each post a user sends is automatically echo'd with an anchor link Comments. As mentioned, when this link is clicked, it will simply expand the div displaying all comments assigned to that thought_id.
Even if there are no comments assigned to the post, I still want the div to expand to display a text field so any user can post a comment, preferably echo this:
<?php
<form action='' method='post' enctype='multipart/form-data'>
<table style='width:850px;'>
<tr>
<td><textarea name='msg' rows='2' maxlength='255' cols='80' placeholder=' add your comment...'></textarea></td>
<td><input type='submit' name='send' value='Share'/> </td>
</tr>
</table>
</form>
?>
Here is what I have so far:
<script language="javascript">
var id = <?php echo $thought_id; ?>;
function toggle(id) {
var ele = document.getElementById("toggleComment" + id);
if (ele.style.display == "block") {
ele.style.display = "none";
} else {
ele.style.display = "block";
}
}
</script>
And here is where the comments anchor link is found. Since it is quite lengthy, I have reduced the echo's content to only the relevant code:
echo "<div class='message_wrapper'>
<div class='where_msg_displayed'>
<div class='more_options' style='float: right;'>
// Options, and display picture of the user who posted the
// thought can be found here.
</div>
</div>
<div class='where_details_displayed'>
<div class='mini_nav' style='float: right;'>
// Below is the comments anchor link.
<a onclick='return toggle($thought_id);' style='padding-left: 5px;'> Comments ($num_of_comments) </a>
</div>
// I expect the following piece below to every comment assigned to the thought_id in the database.
<div id='toggleComment$thought_id' class='new_comment' style='display:none;'>
<br/> $comment_posted_by said: $comment_body
</div>
</div>
</div>";
Other Infomation:
$thought_id is the id of the though the user posts. (table user_thoughts, column id).
I have another table called user_comments, which stores all comments and links it to the thought it is assigned to by post_id.
At the moment, nothing happens when I click comments.

First, here is a working example of what you want to achieve based on your code.
I had to strip the php part off because jsfiddle doesn't interpret it, so next is your code including the PHP bit.
I assumed that you have jQuery loaded as you added the jquery tag to the question.
It's complicated to know why what you tried doesn't work because we're missing important bit such as: how do you load your content into the DOM? dynamically or not (ajax?)
HTML/PHP
<div class='message_wrapper'>
<div class='where_msg_displayed'>
<div class='more_options' style='float: right;'>
</div>
</div>
<div class='where_details_displayed'>
<div class='mini_nav' style='float: right;'>
<a href="#" class="toggle-comment" data-id="<?=$thought_id?>" style='padding-left: 5px;'> Comments (<?=$num_of_comments?>) </a>
</div>
<div id='toggleComment<?=$thought_id?>' class='new_comment' style='display:none;'>
<br/> <?=$comment_posted_by?> said: <?=$comment_body?>
</div>
</div>
</div>
Your link was missing an href attribute, which is mandatory for it to be displayed properly. So we set it to the commonly used "#" which means blank anchor. We will then need to catch the click event on this link and prevent its default action so we don't see that ugly # in our url
You should avoid storing big chunks of html in a php var and then echo it but use html templates instead.
You should avoid mixing PHP and javascript like this line in your code that assign a php var into a js one var id = <?php echo $thought_id; ?>;
Instead, You can store your thought_ids as a data attribute of your links and easily fetch them using jQuery's data() later.
Javascript
$(function() {
$("a.toggle-comment").on("click", function(event) {
// prevents browser to go to href's #
event.preventDefault();
// uses Jquery's data() function to get comment id from link's data-id attribute
var id = $(this).data('id');
// get element by id and toggle display
var ele = document.getElementById("toggleComment" + id);
$(ele).toggle();
});
});
Here I got rid of your toggle() function and replaced it with a handler function using jQuery's on() that get called each time we click on a link that has the toggle-comment CSS class. It has the advantage of working on dynamically added content after the page is loaded. jQuery's on() documentation page does a great job explaining this (and the deprecated live() page too)
Notice that you will need to add this toggle-comment class to every of your Comments (X) links
If you are new to jQuery, you should consider reading this page to understand what the first line does and why you need it. (referring to enclosing your code into $(function() {...});)
event.preventDefault(); tells the browser to not perform its default behaviour when clicking on the link (which is go to that link and would append # to the address bar)
$(this).data('id'); reads put the clicked link (this) into a jQuery object and use data() to get the value of its data-id attribute, which is set to $thought_id
CSS issue update
See my updated fiddle for your CSS issue, I removed the float inline styles and positioned div.mini_nav using absolute positioning relative to message_wrapper.
I think that this issue is not related to the original question and should be asked in another one.

PHP Code as per OP's
<?php
$thought_id = 1;
$num_of_comments = 10;
$comment_posted_by = "Me";
$comment_body = "test comment body";
//hard coded above vars to achieve assumptions
echo "<div class='message_wrapper'>
<div class='where_msg_displayed'>
<div class='more_options' style='float: right;'>
// Options, and display picture of the user who posted the
// thought can be found here.
</div>
</div>
<div class='where_details_displayed'>
<div class='mini_nav' style='float: right;'>
// Below is the comments anchor link.
<a href='' onclick='return toggle($thought_id);' style='padding-left: 5px;'> Comments ($num_of_comments) </a>
</div>
// I expect the following piece below to every comment assigned to the thought_id in the database.
<div id='toggleComment$thought_id' class='new_comment' style='display:none;'>
<br/> $comment_posted_by said: $comment_body
</div>
</div>
</div>";
?>
JavaScript
<script language="javascript">
var id = <?php echo $thought_id; ?>;
function toggle(id) {
var ele = document.getElementById("toggleComment" + id);
if (ele.style.display == "block") {
ele.style.display = "none";
} else {
ele.style.display = "block";
}
return false;
}
</script>
The above code worked for me, as per single record.
Now as you have tagged your question under jQuery
you could simply use
$(".message_wrapper .mini_nav a[href!='']").click(function() {
$(this).parent().next().toggle();
});

You could simply use the <details> HTML tag which acts as a disclosure triangle.
<details>
<summary>View comments</summary>
<ul>
<li>You comments</li>
<li>You comments</li>
<li>You comments</li>
</ul>
</details>
https://developer.mozilla.org/en/docs/Web/HTML/Element/details
The only issue is that it is not supported by the lovely IE browsers.

If I understand your question correctly , this is what you are looking for
https://jsfiddle.net/vrqsz3ev/7/
<div class='message_wrapper'>
<div class="main-msg-container">
<div class='where_msg_displayed'>
<input type="hidden" id="msg-id" value="1">
<div class='more_options'>
MESSAGE1
</div>
<div class='mini_nav'>
<button class="open-comment">comments</button>
</div>
</div>
<div class="hide-mess-details">
<div class='where_details_displayed'>
<div id='toggleComment1'class='new_comment msg-id-1'>
sachin said: Hii guysss (cmt of msg 1)
</div>
<form action='' class="comment-form"method='post' enctype='multipart/form-data'>
<textarea name='msg' placeholder=' add your comment...'></textarea>
<input type='submit' name='send' value='Share'/>
</form>
</div>
</div>
</div>
I made it using jQuery
Some of the things to note while looking into the code is
Uses the concept of flexbox in css3 to style it.
if you click on the share button only the comment of the respective message gets updated . For checking I added a message id along with the form when comment button is clicked .for checking purpose I added an alert (message id of the respective messages) if you click the share button
Now you can add your messages under .where_msg_displayed using php
display all the comments under .where_details_displayed (if you want to , you can add details under there respective messages -little edit is needed)
If you are continuing with this code , with little edits you can achieve the above requirements .

Related

Trying to create a dynamic list item. jQuery

I have a couple of list items, on the left side and aligned vertically. I'm trying to make so that the container on the right side, which is empty, will populate with information from the url for that list item's specific id. I was able to create a jQuery function using load() and it allowed me to click within the list item and data was populated in the right container, but it's only the data for the smallest id. If I click the other list items, the data in the right container doesn't change. Currently, I added this line of code,
var strReqUrl = $(this).attr('href');
alert(strReqUrl);
to see if an alert would display the link it's supposed to be using. When I click within the list item, the alert says "Undefined". :(
I tried adding a link within the list item, and it works. The correct data is shown, however, I leave my current page every time to see it and it doesn't populate in the container on the right at all, which is now on the previous page.
Is there anyway to get the proper id assigned to the proper list item?
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("li").click(function(){
var strReqUrl = $(this).attr('href');
alert(strReqUrl);
//$("#divId").load("pm_message.php?u=<?php echo $log_username; ?>&pmid=<?php echo $pmid; ?> #pm_post");
});
});
<body>
<div class="wrapper"> <!--Left and Right container wrapper-->
<div class="container">
<div class="left">
<!--left container-->
<div class="top">
<input type="text" />
</div>
<ul class="people">
<?php echo $people; ?> <!--generates list of people-->
</ul>
</div>
<div class="right" id="right">
<!--Right container-->
<div class="top"><span class="name"></span></div>
<div id="divId"></div>
</div>
</body>
</html>
And script:
//DB connection
//Collecting data from db
//Variable $people collects data for the people listed in the left container
$people = '
<li class="person">
<a id="a" href="pm_message.php?u='.$log_username.'&pmid='.$pmid.'"><span class="name">'.$sender.'</span></a>
<!--<span class="name">'.$sender.'</span>-->
<span class="time">'.$time.'</span>
<span class="preview">'.$message.'</span>
</li>';
When you assign event handlers, li is not already in the document. You need to use delegated handling. And the href attribute you are looking for is not there. Try this:
$('ul').on('click', 'li', function() {
var strReqUrl = $(this).find('a').attr('href');
alert(strReqUrl);
});
See more - http://api.jquery.com/on/

When I click a link, click a link on another page?

Really struggling to think of a solution to this problem. I have thought anchor links might help (using the #example on the end of a link to scroll to a position on the page) but not sure how best to implement them.
So on the homepage of my site I have a list of links, that correlate to tabs on another page.
The links on the homepage:
(What is e-Bate, What are rebates etc.)
Links
When you click one of the tabs on the other page, it activates a script which shows a certain div below:
Tabs
This is how the tabs are shown:
HTML:
<div class="page-links">
<ul>
<li>What is e-Bate?</li>
<li>What are rebates?</li>
<li>e-Bate features</li>
<li>How e-Bate works</li>
<li>Case studies</li>
</ul>
</div>
<div class="page-contents">
<div id="whatebate" class="hideshowdiv">
<?php echo CFS()->get('whatisebate'); ?>
</div>
<div id="whatrebate" class="hideshowdiv">
<?php echo CFS()->get('what_are_rebates'); ?>
</div>
<div id="ebatefeat" class="hideshowdiv">
<?php echo CFS()->get('e_bate_features'); ?>
</div>
<div id="howebate" class="hideshowdiv">
<?php echo CFS()->get('how_e_bate_works'); ?>
</div>
<div id="casestud" class="hideshowdiv">
<?php echo CFS()->get('case_studies'); ?>
</div>
</div>
jQuery:
jQuery(document).ready(function() {
jQuery(".page-contents div.hideshowdiv").hide();
// Show chosen div, and hide all others
jQuery("a").click(function (e)
{
//e.preventDefault();
jQuery("#" + jQuery(this).attr("class")).fadeIn().siblings('div.hideshowdiv').hide();
});
});
So when one of the links is clicked on the homepage, for instance, the 'What is e-Bate?' link, I want it to go to the other page, and click the corresponding tab, showing the content for that section. Is this possible? Thanks in advance.
This is very possible and you had half the equation with the anchors. Now you just need to write a small function to parse out the URL and check for a certain tag.
So something like this:
$(function(){
if (location.href.indexOf("#example") != -1) {
//This is where you put your function to show the tab
}
if (location.href.indexOf("#anotherexample") != -1) {
//This is where you put your function to show the tab
}
})
Well, if you can use PHP, then it is indeed pretty easy:
First, you need to create a PHP file, obvious with an input parameter, preference, two GET variables, the first one being the link of the page you want to visit and the second one can be, well that depends on how you want it to be, it can be a div id, or a div class or pretty much id of anything you want to click on the second site (You MUST KNOW which button/link you want to click on the second site)
Then first in your php code, store these two things into variables, Let us take $Path and $DivToClick,
Now, use this PHP function:
file_get_contents(path,include_path,context,start,max_length)
Here, the path is an required field, rest is all optional.. and then after that, echo a JQuery code which will do something like this
function ClickTheButton ()
{
$('#divId').click ();
}
Now, let me explain what we are doing here... First, you are sending link to a php script that get all the contents of that webpage and display it on my screen, and then when you are echo-ing the JQuery code, you are telling browser, that yes, this is the part of the page, execute it and simulate the action of click on this page, and thus the click action is simulated and things are done as per your need...
Hope this helps... :)

How to pass viewBag data into Javascript and display in div

I am always leery of asking dumb questions here but I need to move on and create a few more active pages but this is a lingering issue in my way ...The chtml in razor contains a switch ,,, in one of the cases there's three if statements.. THIS IS JUST ONE OF THEM depending on the if statements a different string in viewdata is to be fed into a div and the div class "hidden" is removed and the supplied text displayed....
I have over the past few hours regained my briefly lost ability to remove that hidden class (I hate css) but I have never been able to update the content of the div.
PLEASE Advise Thank you !!
<div id="divUnUsableEvent" class="hidden">
<div class="row clearfix">
<div class="col-md-1"></div>
<div id="systemExceptionLbl" style="font-size: 2em; color: red;"
class="text-danger:focus">
Please contact IS support
</div>
</div>
</div>
//alphascores Not present AND BetaSCores Not Present Ready for xxxxx //alphascores Not present AND BetaSCores Not Present Ready for xxxxx Scoring
if (!Convert.ToBoolean(#ViewData["alphaPresent"])
&& !Convert.ToBoolean(#ViewData["betaPresent"]))
{
<script type="text/javascript">
$(function() {
$('#UnUseableEvent').addClass("hidden");
var txtMsg = #Html.Raw(Json.Encode(ViewData["beforeAlpha"]));
$('#divUnUsableEvent').removeClass("hidden");
$('#systemExceptionLbl').removeClass("hidden");
$('#systemExceptionLbl').innerText = txtMsg;
});
</script>
<a id="XXXReScoreEvent"
href="#Url.Action("Readyforxxxxxx", "Exception", new { Id = (int)#ViewData["Id"] })"
class="btn btn-primary btn-default btn-too-large pull-left margin"
aria-label="XXXReScoreEvent">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Ready for xxxxxx Scoring
</a>
}
break;
I know its hitting the javascript, as that html element (a button) named '#UnUseableEvent' is correctly being hidden in this case. I of course would want the javascript out of this html page and just have function calls in the razor but baby steps
Specifically regarding the ('#systemExceptionLbl').innerText = txtMsg; I have tried
.text
.value
.innerHTML
all to no avail. I can see the correctly formatted Json.Encoded text reach the variable txtMsg, but again I cant get it into the div ..
I am having success now with displaying the div (remove class hidden) I was attempting to affect the wrong div name and the line removing the hidden class from the element $('#systemExceptionLbl') is not needed.
I even tried to skip the JQuery reference and go old school document.getElementById('systemExceptionLbl').innerHTML = txtMsg;
Ever tried :
$('#systemExceptionLbl').text( txtMsg );
or
$('#systemExceptionLbl').html( txtMsg );
as innerText is not a jquery function. Instead use .html() or .text() to insert data into it

Hide/Show div and change class in span with Jquery function

I am using very simple function to hide entire div when clicked and display comments block instead.
Instead of hiding entire div, what I need to do is keep it as it is when clicked, display comment block, but change the class in the span from class="icon expand" to class="icon abate" and hide only "Click here to leave a comment or view what our customers are saying." line so that if it is clicked again it would do the opposite.
here is my script
function myfunc_showComments() {
if ( typeof jQuery != 'undefined' ) {
$('#hidecomments').remove();
}
var commentsParams ={
categoryID: 'Widgets',
streamID: '<?php echo $streamID ?>',
containerID: 'commentsDiv',
}
gigya.services.socialize.showCommentsUI(conf,commentsParams);
}
</script>
<!-- end #review --></div>
<div id="hidecomments">
<div class="button_3" onClick="myfunc_showComments()"><span class="icon expand"></span><h2>Comment & Rate this <span><?php echo $widget_title ?></span></h2><br />Click here to leave a comment or view what our customers are saying.
</div>
</div>
any suggestions or help is highly appriciated
I'd be inclined to put the "Click here..." text that you want to show and hide inside a div of its own:
<div id="hidecomments">
<div class="button_3"><span class="icon expand"></span>
<h2>Comment & Rate this <span><?php echo $widget_title ?></span></h2>
<br />
<div class="instruction">
Click here to leave a comment or view what our customers are saying.</div>
</div>
</div>
...so that it is easier to manipulate from your JavaScript code. Note that I've also removed the inline onClick="myfunc_showComments()" part, because you can just directly bind the handler form your script as follows:
$(document).ready(function() {
$(".button_3").click(function() {
var $this = $(this);
$this.find("span.icon").toggleClass("expand abate");
$this.find("div.instruction").slideToggle();
});
});
The .toggleClass() method adds or removes the specified classes depending on whether they're already there; it can add and remove at the same time so there's no need to manually code an if test to see what the current class is.
The .slideToggle() method is just one of several options that hide an element that is visible or show an element that is not visible. Other options include .toggle() or .fadeToggle().
Working Demo: http://jsfiddle.net/cRjCN/
Note that the document ready wrapper is not needed if the script appears after the elements in question.
use jQuery prop do it like this $(yourselector).prop('class','icon abate');
Edit:
$(".button_3").click(function(e) {
$("span.icon.expand").prop('class','icon abate');
});
just add the code block above inside <script> tags inside your html body tag. preferably before the closing </body> tag.

Help with some jQuery in a Wordpress Loop

I am making a custom archive page, that will display the list of posts with their excerpt, and a button that when clicked toggles the rest of the post content. I have it working with this code, except that it toggles EVERY post content lol because in the loop they all get the class you know what I mean?
Can you help me fin a way to do this? There has to be a way to make it work in the loop right? Here is the (fail) code I have thus far,
Thank you!
`
<div id="more_content">
More
<div class="content_hidden" style="display:none;">
<div class="copy">
<?php the_content(); ?>
</div>
<p class="tags"><?php the_tags(); ?></p>
<?php comments_template(); ?>
</div>
</div>
<script type="text/javascript" charset="utf-8">
$('.see_all').click(function() {
if ( $(this).html() == 'More'){
$('.content_hidden').toggle('slow');
$(this).html('Less');
}
else if ( $(this).html() == 'Less'){
$('.content_hidden').slideUp('slow');
$(this).html('More');
}
return false;
});
`
This should work:
$('.see_all').click(function() {
if ( $(this).html() == 'More'){
$(this).parent().find('.content_hidden').toggle('slow');
$(this).html('Less');
} else if ( $(this).html() == 'Less'){
$(this).parent().find('.content_hidden').slideUp('slow');
$(this).html('More');
}
return false;
});
To quote you:
it toggles EVERY post content lol
because in the loop they all get the
class you know what I mean
What you need to do is address the .content-hidden within or relative to each container of the clicked link, as opposed to addressing all of them at the same time. Furthermore, it is possible that you are repeating IDs within your document (which is bad, forbidden, taboo, don't do, invalid, against spec, won't work, etc). So, your <div id="more_content"> should perhaps instead be <div class="more_content">
Use
<?php the_ID(); ?>
to set the HTML ID of the element, and then Javascript to select for the ID of the container you want to reveal.

Categories

Resources