Help with some jQuery in a Wordpress Loop - javascript

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.

Related

ScrollTo function scrolls past element

I have this simple contact form set up and, since I don't have the development time at this moment, I set this one up using jQuery verification instead of AJAX. This works fine.
But now I would like to have the page scroll down when there are errors in the form. I've downloaded jquery.scrollTo.js and added it to my header.php file. And I have the following script for the scrollTo:
if ($("#front_page_contactformulier span").hasClass("error")) {
$('body').scrollTo('#fp_content_006',4000);
}
Now the weird thing is, when the #front_page_contactformulier span has class error it scrolls past this element (like literally to the bottom of the page).
If I change the script to another element:
if ($("#front_page_contactformulier span").hasClass("error")) {
$('body').scrollTo('#fp_content_005',4000);
}
It works?
I cant for the life of me find out why this is happening? Here is my full code:
HTML
<section id="fp_content_006">
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<article>
<?php if( get_field('koptekst_6') ): ?>
<h2><?php the_field('koptekst_6'); ?></h2>
<div style="display:block;height:2px;width:30px;background:#f60;margin-left:auto;margin-right:auto;margin-bottom:15px;margin-top:15px;"></div>
<?php endif; ?>
<?php if( get_field('content_koptekst_6') ): ?>
<?php the_field('content_koptekst_6'); ?>
<?php endif; ?>
</article>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="row">
<div id="front_page_contactformulier">
<span class="error">Error</span>
</div>
</div>
</div>
</div>
</section>
CSS:
#fp_content_006 {
position:relative;
margin-bottom:90px;
text-align:center;
margin-top:90px;
}
jQuery:
if ($("#front_page_contactformulier span").hasClass("error")) {
$('body').scrollTo('#fp_content_006',4000);
}
Here is a fiddle, and the super weird thing is, it works here.
Check if your jquery.scrollTo.js is included properly in header.php file and remember this from PHP documentation:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
You can find documentation HERE
According to the JS you posted, let me break it down for you
if ($("#front_page_contactformulier span").hasClass("error")) {
$('body').scrollTo('#fp_content_006',4000);
}
The first argument should be the Jquery Object and you just need to wrap your selector with jquery object like this:
$('body').scrollTo($('#fp_content_006'),4000);
As per documentation provided here, you have plenty other ways to scroll instead of selector.
You can find the demo here
Also would like to mention, 4000 is the duration of animation which seems to be pretty high, i would recommend it to be 300 to 800.

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... :)

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

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 .

Write click event dynamically on jquery

Here is the original html
<div class='cl_{{ $gen }}'>{{$gen->name}}</div>
<div class='jl_{{ $var }}'>{{$gen->name}}</div>
After looping over here is the html i got as output
I wanted to do if i click on the class cl_x, then the jl_x should be visible and other should be hidden and by default the first cl_1 should be visible. How can i do this ?
<div class='cl_1'>One</div>
<div class='cl_5'>Two</div>
<div class='cl_6'>Three</div>
<br>
<div class='jl_1'>Alpha</div>
<div class='jl_1'>Andrew</div>
<div class='jl_1'>Christ</div>
<div class='jl_5'>Anto</div>
<div class='jl_5'>Brito</div>
<div class='jl_6'>Oyster</div>
<div class='jl_6'>Beta</div>
Note : All the 1,5,6 are not standard as they are coming from database.
I really can't able to think how to achieve this. Help pls
But Here is what i have tried the logic
Inside Document Ready
Loop over the jquery like html
Write click event to show hide if they cick on cl_*
Trigger the click event for first occurance.
Don't worry about the html generated but the need is to write the jquery events dynamically or something else
But can't able to implement the code pls help
Script :
$(document).ready(function() {
//not sure whether i should loop over the jquery itself or write anything like the element starts with cl-* like that
});
Update :
Here is the Fiddle i have so far
You don't really want to use class for this - a custom data attribute makes sense, though. Like <div class="cl" data-number="{{ $gen }}"> with <div class="jl" data-number="{{$var}}"> on the other elements.
Then inside the $(document).ready(...) you can do something like:
$('.jl').hide().first().show();
$('.cl').click(function(){
$('.jl').hide().filter('[data-number="' + $(this).data('number') + '"]').show();
})
It would also be good to make up more meaningful names than "cl" and "jl" - classes should generally be semantic.
Would move the unique identifiers to a different attribute and add a common class to all the J group
<div class='cl' data-gen="{{ $gen }}">{{$gen->name}}</div>
<div class='jl jl_{{ $var }}'>{{$gen->name}}</div>
JS
$(document).on('click','.cl',function(){
$('.jl').hide().filter('.jl_' + $(this).data('gen') ).show();
})
Add a base "jl" class to all your html that has anything with a "jl_*" so that you will have access to anything overall that has the "jl" class then toggle it hidden or not hidden like so:
HTML:
<div class='cl {{ $gen }}'>{{$gen->name}}</div>
<div class='jl {{ $var }}'>{{$gen->name}}</div>
JS:
$(document).on('click', '.cl', function(e){
var classes = ($(e.target).attr("class").split(' '));
$('.jl').toggleClass("hide");
$('.jl' + "."+ classes[1]).toggleClass("hide");
});
Style:
.hide{
display: none;
}
https://jsfiddle.net/rc368gjp/

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.

Categories

Resources