Including jQuery script on wordpress template [duplicate] - javascript

This question already has answers here:
Wordpress how to use jquery and $ sign
(17 answers)
Why is my javascript file not found by wordpress? and why doesn't my javascript file refresh?
(6 answers)
Closed 5 years ago.
I have a page template which is applied to a specific page on my wordpress page. Usually for all of my other scripts i put them in my footer.php and they load from there beautifully. On this specific page though I want to load a script that only should be running on this page. So in my template i include it like this:
<?php
/**
* Template Name: Template
*/
?>
<?php get_header(); ?>
<script src="<?php echo get_template_directory_uri(); ?>/js/teacher-signup.js"></script>
<?php get_footer( ); ?>
Unfortunately when doing that I only get errors like:
Uncaught TypeError: $(...).whatever is not a function
Is there some way in Wordpress to include a couple of scripts on a specific template only? Or am I missing something?
Thanks in advance

register the script like wp recommends:
wp_register_script('your_file_name', get_template_directory_uri() . '/assets/js/some_file.js', false, null, true);
than enqueue the registered script for that specific page/template
if (is_page('page_name') ) {
wp_enqueue_script('your_file_name');
}
you can also add a conditional for the page template name if you want:
if (is_page_template("template_name.php')

You can make if conditional is_page() in certain page id / page slug for example
<?php if (is_page( 1 )) : ?>
<script src="<?php echo get_template_directory_uri(); ?>/js/teacher-signup.js"></script>
<?php endif; ?>
You can put it on your footer.php theme

Related

Conditional script for a WordPress page

I am trying to include some JavaScript to just one single page of a WordPress based website. Basically, what I've done is in the header.php of the theme, I've put the following:
<?php if( is_page('17')) { ?>
<!--Start of Zopim Live Chat Script-->
<script type="text/javascript">
window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
_.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
$.src="//v2.zopim.com/?2pL2gooCVnWNWjh0QB7IVqRgAiarsW4o";z.t=+new Date;$.
type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
</script>
<!--End of Zopim Live Chat Script-->
<?php }
<?php endif; ?>
When I add this, it breaks the entire site, nothing loads anywhere. I've tried it with and without the
<?php endif; ?>
at the end, thinking that it may be duplicating with the
<?php }
I actually have two different conditional statements I need to add, each for a different page. I don't want to use the plugin that allows PHP & JavaScript in the pages themselves for security reasons, which is what I used to use.
Can anyone tell me what I'm doing wrong, and/or how to add this particular JavaScript to only page #17 (which I'm guessing will also show me how to add a PHP statement and link to single-use stylesheet that I need on a different page)?
It's hard to give a definite answer without seeing the rest of the page code but in my opinion you don't need the <?php endif; ?>.
Simply replace
<?php }
<?php endif; ?>
with
<?php } ?>
and it should work.

How to set a php variable with javascript? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
I am going to set a php variable with javascript, the php variable.
I want to give size of browser to a php variable and then echo best css for that (a kind of responsive website by different css and not css3).
<script src="jquery-1.10.2.js"></script>
<script>
$(function(){
var size=($(document).width());
if(size>300){
<?php
$size="more";
?>
}else if(size<300){
<?php
$size="less";
?>
}
})
</script>
<?php
if($size=="more"){
echo '<link rel="stylesheet" href="index-1024.css"/>';
}else if($size=="less"){
echo '<link rel="stylesheet" href="index-less-1024.css"/>';
}
?>
With this code php variable $size is always 'less'
PHP scripts are executed at server. and Javascripts(jQuery) scripts are executed at your browser. There is no way you can set variables like that. Perhaps consider switching the css entirely in javascript:
script src="jquery-1.10.2.js"></script>
<script>
$(function(){
var size=($(document).width());
//if large screen, swap in large css
if(size>300){
$('#mystyle').attr("href", "index-1024.css");
}
})
</script>
<?php
//load small css as default
echo '<link rel="stylesheet" href="index-less-1024.css" id="mystyle"/>';
?>

Strategy for moving javascript to the bottom in CodeIgniter?

On my site I have one global Javascript file which includes jQuery and code for the drop down menu among other things. Many pages also have custom Javascript for minor page-specific interactions, tables etc.
My current set up on each view is a header.php file, basically covering everything from the doctype through to start of the content, the view file for the specific page, and a footer.php closing out the page.
Currently global.js is linked from the <head>. For performance we should put JS at the very bottom of the page, but I can't figure out a good way to do this. I could add the full script line for global.js with the custom script block, but that means I must add it on every page, even when there is no other Javascript. Any better way to move the JS right to the bottom?
You could put the custom JS in a regular variable or nowdoc (php 5.3.0+), and then echo the variable along with script tags in the footer if it exists. Nowdoc might be preferable because you can use both double quotes and single quotes in your JS and PHP won't parse/escape the text.
someview.php:
<?php
$custom_js = "
alert('custom js ran');
";
?>
<?php
$custom_js = <<<'CUSTOM_JS'
alert("custom js ran (i'm in a nowdoc!)");
CUSTOM_JS;
?>
footer.php:
<?php if(isset($custom_js)) { ?>
<script><?php echo $custom_js; ?></script>
<?php } ?>
Edit 2:
If you don't want to have the javascript in a string, you could have the javascript in a seperate file and then use PHP's file_get_contents() to load it into the $custom_js variable as a string.
Edit:
This is just an aside, but you might look into using the Carabiner library for loading JS and CSS. It's an excellent library. It might not necessarily help with your current problem, but if your global.js is quite large, you could split it up and use Carabiner to compress/concatenate on load. I currently use it to select which JS and CSS gets loaded for logged in and logged out users on my current CI project.
Carabiner on Github
Carabiner on Sparks
Carabiner documentation
Perhaps I missed something - but why cant you just load another view, which only contains the js code?
Your template:
$this->load->view("header.php");
$this->load->view("content.php", $data);
$this->load->view("footer.php", $load_js);
Then inside footer.php:
// start of footer stuff here
$this->load->view($load_js);
</body>
</html>
Then inside page1.php:
<script>
// Your scripts here
</script>
OR:
Your template:
$this->load->view("header.php");
$this->load->view("content.php", $data);
Then inside each "content.php" file:
// Content goes here
$data['load_js'] = "page1.php";
$this->load->view("footer.php", $data);
Then inside single "footer.php" file:
// start of footer stuff here
$this->load->view($load_js);
</body>
</html>
Then inside page1.php:
<script>
// Your scripts here
</script>
The second method is probably more what you want. It does mean you need to call the footer in each content file - but it is literally one line - so your not really repeating yourself - but it gives you complete control inside the content file to specifically any js files to load.
You can expand this an make the $load_js variable an array of js files to load.
I use a set of layouts, which are views that provide the basic structure of the site. Every controller calls a layout and passes into it the content specific for that controller method.
For example, say you have a single layout:
<html>
<head>
<title><?php echo $page->title ?></title>
<?php if (count($page->css)): ?>
<?php for ($i=0; $i < count($page->css); $i++): ?>
<link rel="stylesheet" href="<?php echo $page->css[$i] ?>"/>
<?php endfor; ?>
<?php endif; ?>
</head>
<body>
<?php $this->load->view('header.php'); ?>
<?php $this->load->view($content); ?>
<?php $this->load->view('footer.php'); ?>
<?php if (count($page->js)): ?>
<?php for ($i=0; $i < count($page->js); $i++): ?>
<script src="<?php echo $page->js[$i] ?>"></script>
<?php endfor; ?>
<?php endif; ?>
</body>
</html>
Each page passes in a $page object that contains an array of css and js files. For files that are global, like global.js, you can just hardcode that in at the bottom (same with global CSS at the top). Or, you can set a parent controller that all controllers inherit from. This way you can set up the $page object with default settings (including adding global.js). Then, each controller/method can remove global.js if it's not needed.
Each page also passes in a $content variable with the location of the main view for the page.
You can extend this even further by having multiple layouts and moving some of the HTML into the layout (e.g. 1 column, 2 column, 3 column layouts). In those cases, you may pass in multiple view locations for each column, etc. It's really up to you.
Of course, to keep all JS at the bottom you'd need to move all your page-specific custom JS into JS files. That's actually the best way to go, considering external JS can be cached.
Make a helper function; and load a view where you include that global.js script. Anytime you need global.js to be located at the bottom of the page, just call that helper function.
Another option is to use a template library.
I use this one by Williams Concepts.
It allows you to add JS (and CSS for that matter) for individual class/method calls.
For example:
class foo exends Controller {
public function bar() {
$this->template->add_js('js/jquery.js');
$this->template->add_js('alert("Hello!");', 'embed');
$data = $this->some_model->get_data();
$this->template->write_view('content', 'user/profile', $data;
$this->template->render();
}
}
Using this you can either add the JS as and when required, or add it into the template for the site.
In your case, I would either add the global.js in the footer of the template or define a region in the footer of the template when you can add any JS required.
Controller / add function
public function add()
{
$data['page_title'] = 'Test | Add Details';
$data['js'] = array('details','details2');
$this->load->view('template/header',$data);
$this->load->view('details/add');
$this->load->view('template/footer',$data);
}
in your footer template load all the common scripts that are needed, like jquery.min.js, bootstrap.min.js and so on. later add the below code
footer
<!-- Jquery Core Js -->
<script src="<?= base_url() ?>assets/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap Core Js -->
<script src="<?= base_url() ?>assets/plugins/bootstrap/js/bootstrap.js"></script>
<?php
if(isset($js) && count($js) > 0)
{
for($i=0;$i<count($js);$i++)
{
?>
<script src="<?= base_url() ?>assets/js/custom/<?= $js[$i] ?>.js"></script>
<?php
}
}
?>
</body>
</html>
pass all the js files to be loaded in the array.
If you have a footer.php file that's included on everypage, why can't you just put your js code in that file?

How can I use Joomlas <?php echo $this->template ?> in Javascript?

how could I use <?php echo $this->baseurl ?> or <?php echo $this->template ?> inside of an Javascript script?
Like this:
!window.jQuery && document.write(unescape('<script src="/xxx/<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/js/jquery-1.7.2.min.js" data-mce-type="text/javascript" data-mce-type="text/javascript" data-mce-type="text/javascript" data-mce-type="text/javascript">
or in a script tag which is not in the index.php
<script type="text/javascript" src="/xxx/templates/<?php echo $this->template ?>/js/plugins.js"></script>
JavaScript fundamentally cannot execute any PHP code. Remember that PHP runs on the server, generates an HTML document, and sends it back to the browser. Then JavaScript begins running. This means whatever data you want to use in JavaScript must already be on the page by the time Joomla is finished running.
If you do need to fetch additional content from Joomla, look into using AJAX requests. You could build a page that outputs $this->template, for example, and then request that page from JavaScript in the background.

how move javascript to bottom footer in drupal

for performance issue in drupal
how move javascript to bottom footer in tpl file??
In your theme's page.tpl.php, move the print $scripts; line to the footer. Some modules' JS code doesn't like this, but I've had it work with most.
http://groups.drupal.org/node/8399
I just answered a similar question on Drupal Answers: https://drupal.stackexchange.com/questions/46202/move-aggregated-js-file-to-the-footer/89590#89590
I'm copy pasting the answer below for quick reference.
Also, I'm not sure if the question should be migrated to Drupal Answers or merged or else so if anyone has an idea please execute this or advise on how to do it. Thanks.
Found this excellent code snippet for Drupal 7: https://gist.github.com/pascalduez/1418121
It offers a way to have $script and $head_scripts so that you can specify which JS files need to go in the head. Example, Modernizr should go into the head scripts.
I'm copy pasting below the solution in the link to future proof the answer.
Cheers.
html.tpl.php
<!DOCTYPE html>
<html<?php print $html_attributes; ?>>
<head>
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $head_scripts; ?>
</head>
<body<?php print $body_attributes;?>>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $scripts; ?>
<?php print $page_bottom; ?>
</body>
</html>
template.php
// Used in conjunction with https://gist.github.com/1417914
/**
* Implements hook_preprocess_html().
*/
function THEMENAME_preprocess_html(&$vars) {
// Move JS files "$scripts" to page bottom for perfs/logic.
// Add JS files that *needs* to be loaded in the head in a new "$head_scripts" scope.
// For instance the Modernizr lib.
$path = drupal_get_path('theme', 'THEMENAME');
drupal_add_js($path . '/js/modernizr.min.js', array('scope' => 'head_scripts', 'weight' => -1, 'preprocess' => FALSE));
}
/**
* Implements hook_process_html().
*/
function THEMENAME_process_html(&$vars) {
$vars['head_scripts'] = drupal_get_js('head_scripts');
}
The fastest way to move all Drupal's JS to the footer is by moving $scripts just before the closing body tag AND before $closure.
Within the Drupal 6 core there is no option oder interface which you can easily check. But under admin/settings/performance there are an option to compress JS Files. Recommended for production use.
To put your JS Files to the bottom go to your page.tpl.php file and look for <?php print $scripts;?> or something similar. Then look for $closure; and change it:
<!-- other theme code above -->
<?php print $scripts; ?>
<?php print $closure; ?>
</body>
</html>
I think this should move over to https://drupal.stackexchange.com/questions/3171/add-javascript-at-the-bottom-of-a-page/101025#101025
Where there is a duplicate discussion.
I've found that moving print $scripts at the bottom rarely works. Most of the time, you would need a solution that allows to keep some of the scripts in the header, whilst others can be moved in the footer.
Personally, I use drupal_add_js in template.php taking advantage of the scope option.
From Drupal docs:
scope: The location in which you want to place the script.Possible values are 'header' or 'footer'.If your theme implements different regions, you can also use these.Defaults to 'header'.

Categories