Wordpress - Allow older and newer post buttons navigate to a ID - javascript

I am looking for a way to modify the below PHP to allow the addition of a ID that once pressed will navigate the user to the start of the blog posts instead of the top of the page.
<div class="post-navigation">
<?php next_posts_link( 'Older Posts', $wp_query ->max_num_pages); ?>
<?php previous_posts_link( 'Newer Posts' ); ?>
</div>
I feel like this is somethign that should be possible without a plugin although I have found a plugin that would allow me to do this piece of functionality.
The intended story would go something like this:
User clicks on 'older' or 'newer' button that would have in the url something like domainName.co.uk/page/2#startofposts
The user then would have the browser refresh and instead of the page being loaded at the top it would be loaded where the ID 'startofposts' would be in the DOM.
Anyone done this without a plugin?
Cheers

jQuery(document).ready(function() {
var startID = '#post-container';
var urlString = window.location;
var caseSearch = '/page/'
if(urlString.indexOf(caseSearch) != -1 {
jQuery(window).scrollTop(jQuery(startID).offset().top);
}
}
this should do the trick. There are better ways to do this but for a quick solution id should be fine.

In the end I appended the wanted ID onto the end of the anchors manually.. preventing me from having to do anything too fancy.
$('.post-navigation a').each(function () {
var current = $(this);
var href = current.attr("href");
current.attr("href", href + '#post-container');
});

Related

jQuery Dialogue Box Not Closing

I have a javascript/jQuery cookie confirmation box on my site as shown here: http://jsfiddle.net/x7rAk/1/
var checkCookies = document.cookie;
var cookieNotice = '<div id="continue_box" class="cookie_box"><p>This website uses cookies to improve the user experience. For more information on cookies please see this link. By clicking continue, you agree to the use of cookies.</p><p class="cookies_accept"><span class="cookie_button" id="continue"><img src="/images/tick.png"/><span> Continue</span></span></p></div>';
$('body').ready(function() {
$('body').prepend($(cookieNotice).fadeIn(2000));
});
var continueButton = 'span#continue.cookie_button';
var closeButton = 'span#close.cookie_button';
var closeNotice = '<div id="close_box" class="cookie_box" style="display:none"><p>You have agreed to the use of cookies. This allows us to bring you a better service by remembering your preferences.</p><p class="cookies_accept"><span class="cookie_button" id="close"><img src="/images/cross.png"/><span> Close</span></span></p></div>';
$('#continue_box.cookie_box').ready(function() {
$(continueButton).click(function() {
$('#continue_box.cookie_box').fadeOut(1000, function() {
$('body').prepend($(closeNotice).fadeIn(1000));
});
});
});
$(closeButton).click(function() {
$('#close_box.cookie_box').fadeOut(2000);
});
This is missing images and fonts etc. but it works exactly the same as on my site.
If you run the code, you will see that the box doesn't disappear when you click close.
First of all, how do I fix it, and secondly why does mine not work (I like to know why so I don't have to waste your time again :) ).
Thank you,
Connor
P.S. On my site it checks whether you have a cookie called cookiesAgree before showing it so the code is normally more sophisticated.
This should work
$(document).on("click", closeButton, function() {
$('#close_box.cookie_box').fadeOut(2000);
});
The content is being added dynamically, so you need to register the event handler.

Refresh page with data from $.post()

I am trying to send data to a index page when a link on that page is clicked. the index.php page looks like this:
include "../app/bootstrap.php";
include ("../src/controllers/DisplayContentsController.php");
$data = new DisplayContentsController();
$link = (isset($_POST['link']) ? $_POST['link'] : null);
if ($link != null)
{
$data->show($twig, $starting_file_path . '/' . $link);
$starting_file_path = $starting_file_path . '/' . $link;
}
else
{
$data->show($twig, $starting_file_path);
}
and on the Twig template that is loaded I have this:
<script>
jQuery('.show_content').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery.post(window.location, { link: href });
});
</script>
I want to reload the page with the new link that way it loads the correct directory. But when I do the jQuery.post() the content that is displayed does not change. Can someone help my find out what is going wrong and how I can accomplish this?
The output from the POST request would be returned on the success handler function. For example, you would need to do something like this:
jQuery('.show_content').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery.post(window.location, { link: href } , function(data){
//data will have the new HTML after the page posted back. You can use that
//HTML to load if onto an element on the page. Something like:
$('#content_result').html(data);
});
});
Assuming you have a div with "id = content_result" -or something like that- that you can use to load the HTML into it.
If you want to append the result to the existing HTML already displayed inside #content_result then simply do:
$('#content_result').html($('#content_result').html()+data);
Now, keep in mind that this will return everything - the full page - and if you blindly keep appending things, you'll end up with a page that does not conform to valid HTML -for example, a page with more than 1 <head>,<body> sections, etc. The best thing to do is to extract the section that you really care about, and append only that section such that you always end up with a valid HTML document.
jQuery offers plenty of options to do this sort of thing.

Function to find string on page and click link next to it?

I'm wondering whether it is possible to devise a script which will search a webpage for a certain string of text, and then click the link in the element id directly to its right.
Is this possible. Maybe javascript, php?
Please help, and thanks to all that do. :)
#Four_lo
Thanks for your reply. I'm sorry, maybe it's because I'm pretty new to javascript, but I can't really understand anything on the page you suggested.
I put together some javascript which will search the page for an element id and click the link within there.
<html>
<head>
<script type="text/javascript">
function init(){
var linkPage = document.getElementById('linkid').href;
window.location.href = linkPage;
}
onload=init;
</script>
</head>
<body>
GO HERE
I WANT TO CLICK HERE!
</body>
</html>
So basically, I need to search the page for GO HERE. Then, once this is found, I need to click the link in id="thisone", if that makes sense.
The above code works, and clicks the link within the id specified. However, I'd like to find certain text within that id, then move onto the next id, and click the link within that id.
It is possible. It will probably take some finesse but here is where you should start to access String you need. I believe regular expressions will be a must as well.
http://dom.spec.whatwg.org/#processinginstruction
http://domparsing.spec.whatwg.org/
Slightly more complicated than it needs to be:
function performAfterLinkWithText(text, perform) {
// get all the links
var $links = document.getElementsByTagName('a');
// scan them for your text
for(var i in $links) {
if($links[i].innerHTML === text) {
var $next = $links[i] // ready for loop
, terminateAfter = 20 // don't repeat forever
;
// keep checking the adjacent element
// because newlines show up as #text
do {
$next = $next.nextSibling;
} while( !$next.href && terminateAfter-- > 0 );
// do your thing
perform($next.href, $next); // window.location.href = $next.href;
}
}
}
// test -- performAfterLinkWithText('GO HERE', function(url, link) { console.log(url, link); });
performAfterLinkWithText('GO HERE', function(url) { window.location.href = $next.href; });
Or with jQuery:
window.location.href = $('a:contains("GO HERE")').next().attr('href')

anchor jumping by using javascript

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.
I have two problems regarding anchors.
The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.
So the structure of the anchors is:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<div class="wrap">
<a name="one">text 1</a>
<a name="two">text 2</a>
<a name="three" class="box">text 3</a>
</div>
Okay, if you will click one of the links the url will automatically change to
www.domain.com/page#1
At the end this should be just:
www.domain.com/page
So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.
I have found this function:
function jumpto(anchor){
window.location.href = "#"+anchor;
}
and calling that function with:
<a onclick="jumpto('one');">One</a>
what will be the same like before. It will add the hash to the url. I also added
<a onclick="jumpto('one'); return false;">
without success. So if there is someone who could tell me how to solve this I really would appreciate.
Thanks a lot.
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}​
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
I don't have enough rep for a comment.
The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).
Something to bear in mind if you don't have control of the document markup (e.g. webextension).
The location based method in the selected answer can also be simplified with location.replace:
function jump(hash) { location.replace("#" + hash) }
Because when you do
window.location.href = "#"+anchor;
You load a new page, you can do:
One
<script>
function getPosition(element){
var e = document.getElementById(element);
var left = 0;
var top = 0;
do{
left += e.offsetLeft;
top += e.offsetTop;
}while(e = e.offsetParent);
return [left, top];
}
function jumpTo(id){
window.scrollTo(getPosition(id));
}
</script>
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
Test link
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ☺
The first suggested solution of accepted solution did not work for me entirely. The main problem was when it was already jumped to hash, and hash already in url, jump did not happen again. I propose here, for the sake of completeness, somewhat more elaborate solution which works (tested in Chrome and FF). el is element with anchor tag.
el.addEventListener('click', function(ev) {
ev.preventDefault();
const href = ev.target.getAttribute('href');
const hashIndex = href.indexOf('#');
if (hashIndex !== -1) {
const hashPart = href.substring(hashIndex);
if (location.hash === hashPart) {
document.querySelector(hashPart).scrollIntoView();
}
else {
location.hash = hashPart;
}
}
})

Javascript substring method assistance

So long story short im working on a web app and using AJAX within it.
I'm trying to disable the default actions of links when clicked, attach a hash value to the link and then remove the "#" from the url.
the problem im having is that, although the hash values are being attached accordingly, the substring method isnt extracting the "#", it extracts the letter after it.....
here is my code. PS, i left my comments inthere so you get where im trying to go with this
so i dont know....my logic or setup may be wrong....
$(document).ready(function(){
//app vars
var mainHash = "index";
var menuBtn = $('.leftButton');
//~~~~~~load the index page at first go.
loadPage();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~menu show/hide
menuBtn.click( function(){
$('#menu').toggleClass();
});
//Menu items on click , disable link default actions.
$('#menu a').click( hijackLinks );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~functions for mobile index load AND hijacking app links to AJAX links.
function loadPage(url){
if( url == undefined){
$('#contentHere').load('index.html #content', hijackLinks);
window.location.hash = mainHash;
} else {
$('#contentHere').load(url + '#content', hijackLinks );
}
}
function hijackLinks(e){
var url = e.target.href;
e.preventDefault();
loadPage(e.target.href);
window.location.hash = $(this).attr("href").substring(1);
}
});
what im wanting is to remove the "#" from the url. What am i doing wrong, what am i not seeing/understanding?
ive tried substring/substr etc and both do the same thing in that no matter what numbers i choose to insert into the substrings params, they remove EVERYTHING BUT the "#" lol....
Thanks in advanced.
Well, you don't really change the link itself, you only change the window.location.hash, and the hash always has a "#" at the beginning.
What you need to do in order to change the entire url (and remove the '#') is to manipulate the browser history.
Although you should know it works only in newer browsers (the exact browser versions are in the link), so if you target your website to older too browsers you might need to think about having a fallback using the hash. If you decide to have such a fallback, I suggest searching for a plugin which does it instead of making it all yourself.

Categories