Overriding a javascript function in a Wordpress Child Theme - javascript

I am writing a simple Wordpress child theme.
There is a portfolio feature which uses flexslider to display the thumbnail from the most recent posts and, when clicking on them, it uses ajax to open up the post content in a div on the page.
I have written a category page based on this, which pulls out all the post categories and displays the thumbnail for the most recent post. However, when I click on the thumbnail, I need the page to go to a new page and not open up in the content div.
The problem is, I am reusing code which looks a bit like this:
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="flexslider">
<ul class="slides">
<li>
<a href="http://the-url-here">
<img src="<?php echo $thumb[0]; ?>" />
</a>
</li>
</ul>
</div>
<?php endwhile; ?>
But there is custom js within the parent theme global footer as follows which handles the opening up of the content, rather than redirecting to the location specified in the tag as usual.
$(".flexslider ul.slides li a").live('click', function(e){ e.preventDefault();
/*Set Function Variables */
$this = $(this);
$selectedthing = $this;
$postId = $($this).attr('data-url');
// and so on...
return false;
});
So, I need to disable the javascript attached to .flexslider ul.slides li a on that one single page template only, preferably without having to change the classes, as I think thatwould open up another can of worms around the css. Remember the theme loads the javascript in the footer, so I assume any changes Imake in the page template will be overridden in the footer.
Any ideas on the best way to approach this?

Just remove click live listener in your child theme. Add this javascript only for that specific page template.
$(".flexslider ul.slides li a").die('click');

Related

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

Load js when visible

I have a phtml page that has separate tabs
<div id="maintabs">
<ul id='mainTabNav'>
<li>Tab 1</li>
<li>Tab 2</li>
</ul>
<div id="maintabs-1">
<p><?php require_once VIEW_DIR."somewhere/tab1.phtml"; ?></p>
</div>
<div id="maintabs-2">
<p><?php require_once VIEW_DIR."somewhere/tab2.phtml"; ?></p>
</div>
</div>
Each tab/page has a header with a js source specific to the page like this
<script src="js/tab<num>.js"></script>
On the page load though each javascript file is loading. Is there a way to only load the js for the tab currently open? When a new tab opens then the js reloads with just the js for the current tab?
You could keep click events on each of the main tabs that would dynamically load the appropriate javascript using something like jQuery.getScript().
$('div[id^="#maintabs"]').click(function(e){
var tabno = $( this ).index();
$.getScript("js/tab"+tabno);
});
The pitfall I'd imagine with this is that you seem to want to have all the previous javascript to be washed away once the latest JS file was loaded. I'm not sure if that's doable or if you'll have side effects from it.
Also this could totally be done with vanilla JS but well, time savings.
Is there a way to only load the js for the tab currently open?
Since you are using PHP you could manage to pass the number of the current page to view. Pseudo-code
View::factory('templateView')
->set('page_number', $page_number)
The $page_number variable now holds the page number that can be used in your scripts with ease
<script src="js/tab<?php echo $page_number; ?>.js"></script>
...
<div id="maintabs">
<ul id='mainTabNav'>
<li>Tab 1</li>
<li>Tab 2</li>
</ul>
<div id="maintabs-".<?php echo $page_number; ?>>
<p><?php require_once VIEW_DIR."somewhere/tab".<?php echo $page_number; ?>.".phtml"; ?></p>
</div>
</div>
Can't you just put this:
<script src="js/tab<num>.js"></script>
into your somewhere/tab*.phtml?
Using pure Javascript, I believe it is possible if you are loading the page using AJAX.
This tutorial, http://code.tutsplus.com/tutorials/how-to-load-in-and-animate-content-with-jquery--net-26, demonstrates a way of loading another page (I call them child pages) into the main page (which I call the index page). As far as I can tell, if you include associated script tags in the child pages rather than the index page, then they are dynamic in that they load when the child page loads, and unloads when he child page unloads.
I have used a modified version of this tutorial in my own projects before, where I don't create the child pages with the same content as the index page as the tutorial shows, and instead use the whole child html file solely for only the child page's content.
Here’s an example based off your code:
indexScript.js :
/* When index.html is loaded and ready */
$(document).ready(function() {
/* Handels on-click of menu buttons */
$('#mainTabNav a').click(function(){
/* Getting the linked page */
var toLoad = $(this).attr('href');
/* Hiding content and calling loadContent function - creates animation*/
$('#contentDiv').hide('slow', loadContent);
/* Injects content to contentDiv div tag */
function loadContent(){
$('#contentDiv').load(toLoad, '', showNewContent);
}
/* Shows contentDiv div */
function showNewContent() {
$('#contentDiv').show('normal');
}
demonstratePageChange(); //For testing - you can remove this
/* In order to stop the browser actually navigating to the page */
return false;
});
/* Initial Load - load first child page by simulation of clicking on it*/
$('#maintabs_1').click();
});
/* To demonstrate the respective JS script is loaded as needed */
function demonstratePageChange() {
setTimeout(function(){
alert(testMsg); //Alerts the message from resepctive child page script
}, 3000);
}
index.html :
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id='maintabs'>
<ul id='mainTabNav'>
<a id='maintabs_1' href='childA.html'><li>Tab 1</li></a>
<a id='maintabs_2' href='childB.html'><li>Tab 2</li></a>
</ul>
</div>
<div id='contentWrapper'>
<div id='contentDiv'></div>
</div>
</body>
<script type='text/javascript' src='jquery-2.1.1.min.js'></script>
<script type='text/javascript' src='indexScript.js'></script>
</html>
childA.html :
<div id='maintabs-1' class='contentBody'>
<script type='text/javascript' src='childAScript.js'></script>
Child A - Page
</div>
childAScript.js :
console.log("childAScript has been loaded");
var testMsg = "This is Child A";
childB.html :
<div id='maintabs-2' class='contentBody'>
<script type='text/javascript' src='childBScript.js'></script>
Child B - Page
</div>
childBScript.js :
console.log("childBScript has been loaded");
var testMsg = "This is Child B!!!!";
However, there are few things to consider using this method:
This particular method requires jQuery
This method doesn't support reload, you'd have to code that in. i.e. if you're on tab 2, you need store that fact and on refresh, point back to tab 2.
Local testing - as far as I can tell, only FF supports this when testing it locally. If you want to test this on Chrome for example, you'd need to upload this onto a server and only then will this work. This is due to the "XMLHttpRequest cannot load" error, if you try this locally.
I hope this helps and resolves your problem.
The use of AMD requirejs can do this also. It is possible to use pure js although I prefer AMD modules [i.e. define()]. For my apps depending on user actions, code is downloaded on the fly reducing load. An onclick event fires on the tab control calling requirejs and the script get downloaded and you call it. PsuedoExample:
<script type="text/javascript" src="require.js"></script>
$(document).ready(function() {
//Assuming using jQuery, use document.getElementById and what not otherwise
$('#maintabs-1').click(function(e) {
require(['/js/tabnum1.js'], function (tab1) {
tab1(doStuff);
});
});
}
Use a for loop for multiple tabs. Also, I try and put as much processing [sans data storage and server validation (obviously)] into the client side.

Using jquery load() to add content into tabbed navigation

I have a web application that uses tabbed navigation from a UI kit: http://www.getuikit.com/docs/tab.html.
Each tab will load different content, which is broken down into several php scripts, one per tab.
One (not very efficient, but so for successful) option is to load up all of the tabs content when the page first loads, so to use the standard example:
<!-- This is the container of the toggling elements -->
<ul data-uk-switcher="{connect:'#my-id'}">
<li><a id="1" class="load-tab" href="">Tab 1</a></li>
<li><a id="2" class="load-tab" href="">Tab 2</a></li>
</ul>
<!-- This is the container of the content items -->
<ul id="my-id" class="uk-switcher">
<li><?php require('script1.php'); ?></li>
<li><?php require('script2.php'); ?></li>
</ul>
I want to avoid this though, because the scripts are quite hefty so want to load them on demand for better user experience.
So what I've done is instead add holding divs and target them with a jQuery load():
<!-- This is the container of the content items -->
<ul id="my-id" class="uk-switcher">
<li><div id="1"></div></li>
<li><div id="2"></div></li>
</ul>
jq:
$(document).on("click", "a.load-tab", function(){
//get the value of the tab clicked in the nav
var tab = $(this).attr('id');
//determine the filename to load based on tab clicked
if (tab == '1'){ var filename = 'script1.php'; }
if (tab == '2'){ var filename = 'script2.php'; }
//load it
$( "#"+tab+ ).load( filename );
});
This works fine ... ish.
Question is this: With the initial (non jquery) method, each script could use the main page's core files that have already been included, e.g. header.php, functions.php etc etc. But when the content is loaded from jquery it seems each script needs to be included in the scipt1.php file and loaded again, which results in duplicate content being created in the DOM.
EDIT
script1.php currently is structured something like:
<?php
require('header.php');
require('connect.php');
require('setUser.php');
require('setParams.php');
require('functions.php');
?>
<div id="header">
//header content
</div>
<table>
//table content
</table>
The page that the navigation sits within, let's just call it index.php for now, already must have those php files included, so you can see the duplication issue.
What can be done to avoid this? Thought of a few options like iframes but seems like it might be a hack.
Your issue is essentially inside 'script1.php' you have something that requires 'connect.php' / data that is populated. But you are doubling up on DOM elements when you pull that in.
Two solutions to that issue are: 1 - create slimmer versions of your lib php files that don't include any DOM elements, only the data required to populate script1.php's data, or
script1.php contains
<?php
require('header.php');
require('connect.php');
require('setUser.php');
require('setParams.php');
require('functions.php');
?>
<div id="header">
//header content
</div>
//Everything inside #content is what you want to pull in
<div id="content">
<table>
//table content
</table>
</div>
And then call
$("#1").load("script1.php #content");
This will only load the HTML that is inside the #content div.

Set a CSS class on the current page in a menu

I have a static website, but I have included different bits of the page (head, header, image slider, footer) by php's include function, to make the website manageable.
Now the problem is that the current page's name in the menu-bar must have selected="selected" to show the current page's name pressed in the front end.
I made a solution of giving every menu-item an id and than injecting the following code to end of every page and setting that page's id (the home button id selected in the example code).
<script type="text/javascript">
$(document).ready(function() {
$('#home').addClass('active');
});
</script>
Now the problem is that I must include this script in every page and to change the id to that page (eg in the above script I have pasted the code in the home page,
I wanna have a solution where I add only once chunk of the code to my footer.php and it automatically detect the current page and set the select="selected" for that menu-item.
Thank You all in advance...
In PHP, you can put the active class on your menu definition (if it's the same on every page), if you know the current page visited:
<ul>
<li <?php if($current_page == 'home') echo 'class="active"'; ?>>Home</li>
<li <?php if($current_page == 'blog') echo 'class="active"'; ?>>Blog</li>
<li <?php if($current_page == 'contact') echo 'class="active"'; ?>>Contact</li>
</ul>
and so on... You don't need Javascript for this (which is disable by some users). The only need is to get the $current_page variable, which can be based on the URL or the ID of the page, depending on your current website architecture.
The solution I discovered for my (specific) problem is,
I gave id(s) to all the menu-items, and those ids were the namesake of the related files (the files to which they'll link), for example the button which links to the home.php was given the id of "home" and the button which was linking to the profile.php was given the id of "profile" than included the following code in the footer
<?php
$php_self = $_SERVER['PHP_SELF'];
$basename = basename($php_self);
$id = basename($basename, ".php");
?>
<script type="text/javascript">
$(document).ready(function() {
$('#<?php echo $id; ?>.addClass('active');
});
</script>
( jQuery used, but if the website doesn't have jQuery already, than the document.getElementById must be used ).
Thank You all for Your time..
You can use js and php together:
$(document).ready(function(){
$("#<?=$current_page?>").addClass('active')
})
It's shorter than Maxime Lorant's code...
Or if your url is something like site.com/#home , this is the solution:
Get css id from url (without php/js)

Check referrer and find the href that leads to it, then trigger a click with javascript

I'm working on a WP single page portfolio that loads post content with AJAX. I read that WP doesn't need #! URLs to make it crawlable by Googlebot. If I understand it correctly, since Googlebot won't interpret ajax, it will just follow the link and index the article page.
So I removed #! from my URLs and when a post is opened I update them with .pushState.It's working fine, but if I hit F5 or if I try to load a specific URL (not the home) I fall into the page of the post (single.php).
To prevent it, I added a javascript redirection in single.php that leads users to the homepage. Then I need to open the content of the article on the homepage.
Here is the address of my site: http://www.youpiemonday.com/ (the redirection isn't online yet).
How can I tell the browser "if you're coming from this page (the referrer), trigger a click on the thumbnail which href is corresponding" (the click will load the content)?
I'm digging around this but I have no idea how to target the thumbnail correctly...
<script type="text/javascript">
$referer = document.referrer; // where we come from
$LinktoRef = $('.ProjectWrap').find("a").href; // the href in the thumbnail
console.debug($LinktoRef); // still undefined...
if ( $LinktoRef == $referer ){
find("a").trigger('click');
}
</script>
Here is what the html markup looks like:
<div id="portfolio-list">
<div class="ProjectWrap">
<?php the_post_thumbnail(); ?>
<a href="<?php the_permalink(); ?>">
<div class="contentProject">
<h4 class="ProjectTitle"><?php the_title(); ?></h4>
</div>
</a>
</div>
<div class="ProjectWrap">//same as above</div>
<div class="ProjectWrap">//same as above</div>
// and the list goes on...
</div>
I'm not really a programmer so any help would be very appreciated. And if you can comment your code, that would be invaluable to me.
Because you are probably trying to reference the element before it is rendered on the page. Use document ready or window onload and reference the link there.

Categories

Resources