Jquery only works in the header.php - php

I'm reading up all I can on jQuery, but this week I like(need) to finish a website and I could find a solution to this problem in the last eight hours.
Setting
I'm using a ajaxed wp theme which I'm customising to my own liking.
Problem
I've wrote a simple function to change the header image and the header text when you click on the main navigation links.
The function does work in the header.php but doesn't work in a custom front page (main_navp.php) I've included in index.php.
On navp.php there's an image when onclicked should do the same changes as a click on the nav bar.
index.php
<?php get_header(); ?>
<div id="main-content"><div id="inside">
<?php get_template_part('main_navp'); ?>
<?php if// HERE IS THE WP LOOP (not used so left out) //?>
<div class="pagination">
<span class="older"><?php next_posts_link('« Older Entries') ?></span>
<span class="newer"><?php previous_posts_link('Newer Entries »') ?></span>
</div>``
<?php else : ?>
<h1>no posts...</h1>
<?php endif; ?>
</div></div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
The function is included in the header.php in the ..head>
<script type="text/javascript">
$(document).ready(function()
{
$("a[title='Gigs']").click(function()
{
$("#main_logo").css("background-image","url(<?php bloginfo('stylesheet_directory'); ?>/images/header/gig_header_flip.png)");
$("a#nav_text").html("Gigs");
});
$("a[title='Bio']").click(function()
{
$("#main_logo").css("background-image","url(<?php bloginfo('stylesheet_directory'); ?>/images/header/play_header.png)");
$("a#nav_text").html("Biography");
});
$("a[title='Gitaarles']").click(function()
{
$("#main_logo").css("background-image","url(<?php bloginfo('stylesheet_directory'); ?>/images/header/les_header.png)");
$("a#nav_text").html("Gitaarles");
});
$("p[id='les_mp']").live("click", function()
{
$("#main_logo").css("background-image","url(<?php bloginfo('stylesheet_directory'); ?>/images/header/les_header.png)");
$("a#nav_text").html("Gitaarles");
});
$("li[id='homew']").click(function()
{
$("#main_logo").css("background-image","url(<?php bloginfo('stylesheet_directory'); ?>/images/header/header_arty.png)");
$("a#nav_text").html("Home");
});
});
</script>
In the main_navp.php (included in index.php afther the header.php) the function does not work on this item. But it should be triggered by $("p[id='les_mp']").live("click", function() as seen above.
<div id="boxred_b">
<div class=head_box><a>Gitaarles</a></div>
<p class="homeles" id="les_mp">
<img src="<?php bloginfo('stylesheet_directory'); ?>/images/les_mp.jpg" />
</p>
The main jquery is caled in the header.php
<script src='<?php bloginfo('template_directory'); ?>/js/jjquery-1.5.2.min.js'></script>
In the footer.php are all of the rest of the jquery functions.
<!-- http://benalman.com/projects/jquery-urlinternal-plugin/ -->
<script src='<?php bloginfo('template_directory'); ?>/js/jquery.ba-urlinternal.min.js'></script>
<!-- http://www.asual.com/jquery/address/ -->
<script src='<?php bloginfo('template_directory'); ?>/js/jquery.address-1.3.2.min.js'></script>
<script>
// Original JavaScript by Chris Coyier
// Updated October 2010 by Stewart Heckenberg & Chris Coyier
$(".home li.home").removeClass("home").addClass("current_page_item");
$("#column-wrap").append("<img src='<?php bloginfo('template_directory'); ?>/images/ajax-loader.png' id='ajax-loader' />");
$("#s").focus(function() {
if ($(this).val() == "Search...") {
$(this).val("");
}
});
if ($(".widget_categories li").length%2 != 0) {
$(".widget_categories ul").append("<li><a> </a></li>");
}
if ($(".widget_tag_cloud a").length%2 != 0) {
$(".widget_tag_cloud").append("<a> </a>");
}
// The reason this JavaScript is in footer.php instead of its own file is basically the next line.
var base = '<?php bloginfo('url'); ?>',
$mainContent = $("#main-content"),
$ajaxSpinner = $("#ajax-loader"),
$searchInput = $("#s"),
$allLinks = $("a"),
$el;
$('a:urlInternal').live('click', function(e) {
$el = $(this);
if ((!$el.hasClass("comment-reply-link")) && ($el.attr("id") != 'cancel-comment-reply-link')) {
var path = $(this).attr('href').replace(base, '');
$.address.value(path);
$(".current_page_item").removeClass("current_page_item");
$allLinks.removeClass("current_link");
$el.addClass("current_link").parent().addClass("current_page_item");
return false;
}
// Default action (go to link) prevented for comment-related links (which use onclick attributes)
e.preventDefault();
});
$('#searchform').submit(function() {
var s = $searchInput.val();
if (s) {
var query = '/?s=' + s;
$.address.value(query);
}
return false;
});
$.address.change(function(event) {
if (event.value) {
$ajaxSpinner.fadeIn();
$mainContent
.empty()
.load(base + event.value + ' #inside', function() {
$ajaxSpinner.fadeOut();
$mainContent.fadeIn();
});
}
var current = location.protocol + '//' + location.hostname + location.pathname;
if (base + '/' != current) {
var diff = current.replace(base);
location = base + '/#' + diff;
}
});
</script>
</div>
I've tried to keep things as short as possible. If you like any more information please ask.
-update
using the live function in the header doesn't seem to solve the problem.
I'm using XAMPP to run the website locally. If it helps I could make an online wp installation or could provide the webside (html/java) source.

Because you are Ajax-ing your page, the events are not subscribed to your new elements. Try using the .live() command.
Also, is this ok?
$("p[id='les_mp']").click(, function()...
Don't know for sure about that comma.

I've tried using the live function in the code like this.
$("p[id='les_mp']").live("click", function()
{
$("#main_logo").css("background-image","url(<?php bloginfo('stylesheet_directory'); ?>/images/header/les_header.png)");
$("a#nav_text").html("Gitaarles");
});
in the
$(document).ready(function()
{ .... }
in header.php
Still it doesn't work when be onclicked in main_nav.php
When I put the code out of the main_nav in to the header.php
it works.

You may want to use the method in the link below to refactor the ajax stuff to a separate file. Not sure if it helps with the original problem, but i've seen things work after doing that http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#js-global
basically you get your url into a variable that is being printed and your scripts have access to using wp_localize_script

Related

How to load Jquery when using multiple php files

I have divided my html-file into a header.php, content.php and footer.php
I would like to load the js files and the document.getready function either in the hader or in the footer file. But I got an error saying: Uncaught ReferenceError: $ is not defined.
In my header.php I load the following scripts in the head section:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" async></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.js" async></script>`
And in my Footer after the closing </body>-Tag I call:
<script>
$(document).ready(function() {
if( !window.isCMS) {
// Group images by gallery using data-fancybox-group attributes
var galleryId = 1;
$('.editable-gallery').each( function() {
$(this).find('a').attr('data-fancybox', 'gallery-' + galleryId++);
});
$('.editable-gallery').each( function() {
$(this).find('img').attr('width', '200');
});
// Initialize Fancybox
$("[data-fancybox]").fancybox({
// Use the alt attribute for captions per http://fancyapps.com/fancybox/#useful
//beforeShow: function() {
// var alt = this.element.find('img').attr('alt');
//this.inner.find('img').attr('alt', alt);
//this.title = alt;
//}
});
}
});
</script>
In my content.php file I include my header.php and footer.php like this:
<?php include ("header.php"); ?>
<?php include ("footer.php"); ?>
How and where do I have to implement the script files and the document.getready function?
This is my Gallery Code in my content.php:
<div id="my-gallery" class="editable-gallery">
<img src="fotos/2018/rl/02022018/3.jpg" alt="">
<img src="fotos/2018/rl/02022018/1.jpg" alt="">
<img src="fotos/2018/rl/02022018/3.jpg" alt="">
</div>
I have to add the attr "data-fancybox" and "width" to work with fancybox.
1st:- The error comes from src="http://code.jquery.com/jquery-latest.min.js" it should be https instead of http >> src="https://code.jquery.com/jquery-latest.min.js"
2nd:- you can include js files or js code in <head> OR BEFORE </body>
3rd:- you can use <script></script> anywhere from <head> to </body> even before the line you including your jquery BUT use $(document).ready(function(){ //code here })
Note: if you have any plugins you must include the plugins after including jquery
your js code works fine
$(document).ready(function() {
//if( !window.isCMS) {
// Group images by gallery using data-fancybox-group attributes
var galleryId = 1;
$('.editable-gallery').each( function() {
$(this).find('a')
.attr('data-fancybox', 'gallery-' + galleryId++).find('img').attr('width' , '200');
});
// Initialize Fancybox
$("[data-fancybox]").fancybox({
// Use the alt attribute for captions per http://fancyapps.com/fancybox/#useful
//beforeShow: function() {
// var alt = this.element.find('img').attr('alt');
//this.inner.find('img').attr('alt', alt);
//this.title = alt;
//}
});
//}
});
<!-- 1. Add latest jQuery and fancyBox files -->
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js"></script>
<!-- 2. Create links -->
<div id="my-gallery" class="editable-gallery">
<img src="http://via.placeholder.com/350x150" alt="">
<img src="http://via.placeholder.com/350x150" alt="">
<img src="http://via.placeholder.com/350x150" alt="">
</div>
<!-- 3. Have fun! -->

Change Visited Link

I have this code:
<div class="menuList">
<li><img src="/images/icon/arena.png" alt="">Arena<span class="green"> (+)</span>
</li>
</div>
And i want to remove <span class="green"> (+)</span> after users click that link.
Anyone can help me (php code)?
As already mentioned, PHP is not the ideal language to do this in. But, if you need to use PHP, here is how you could do it.
Set a session variable on the /arena/ page, like this;
<?php
session_start();
$_SESSSION['visited'] = 1;
?>
Then, use PHP to check for the session variable in your HTML code like this:
<div class="menuList">
<li><a href="/arena/"><img src="/images/icon/arena.png" alt="">Arena
<?PHP
If(isset($_SESSION['visited'])){
echo '<span class="green"> (+)</span>';
}
?>
</a>
</li>
</div>
You will need to add session_start() to the top of the page wherever you are accessing session variables, before you output anything to the page (e.g. DOCTYPE declaration.)
in Jquery you may do this like
<script>
$(function(){
$('.menuList').find('a').click(function(){
$(this).children('.green').remove();
});
});
</script>
You can accomplish this by adding this javascript to your page:
<script>
window.onload = function() {
var a = document.querySelector('.menuList a');
a.onclick = function() {
var span = a.querySelector('.green');
a.removeChild(span);
}
}
</script>
OR if you're using jQuery:
<script>
$(document).ready(function(){
$('.menuList').find('a').click(function(){
$(this).find('.green').remove();
});
});
</script>

Load new page in div part 2

I have managed to load the new page into the div (thanks to everyone for your help) but it looks pretty bad (got menu bar and logo, but I only wanted the content), so instead I need to load only a div from the new page. I tried a new script but got redirected to the new page. Please help.
<script>
jQuery(document).ready(function() {
jQuery('.stil_link_img a').click(function(){
var x = $(this).attr("href") + "#content_eco";
jQuery("#new_page").load(x);
return false;
});
});
</script>
<div id="pachete">
<?php
$result=mysql_query("SELECT* FROM imagini");
while($data=mysql_fetch_row($result)){
if( ($data[3]==1)&&($data[2]==2) ){ ?>
<div class="stil_link_img">
<img src="upload/<?php echo $data[1];?>">
</div>
<?php }
}?>
</div>
<div id="new_page">
//some content which should be replaced with my loaded page
</div>
jQuery(document).ready(function() {
jQuery('.stil_link_img a').click(function(){
var $pageContent = jQuery('<div/>').load($(this).attr("href"));
jQuery("#new_page").html(jQuery("#content_eco",$pageContent).html());
return false;
});
});
I assume #content_eco is the divisions ID in the new page(the url from href attribute).
or you can load just the content from the url and avoid the link postback as
<script>
jQuery(document).ready(function() {
jQuery('.stil_link_img a').click(function(){
var x = $(this).attr("rel") + " #content_eco";
jQuery("#new_page").load(x);
return false;
});
});
</script>
<div id="pachete">
<?php
$result=mysql_query("SELECT* FROM imagini");
while($data=mysql_fetch_row($result)){
if( ($data[3]==1)&&($data[2]==2) ){ ?>
<div class="stil_link_img">
<img src="upload/<?php echo $data[1];?>">
</div>
<?php }
}?>
</div>
<div id="new_page">
//some content which should be replaced with my loaded page
</div>
Hope this helps you.

simple jquery slideshow issue

I'm having a problem with a simple jquery slide-show (English is not my first language so I'll try to explain it). I have my index.php in which I place the slideshow.html by using jquery. Here's the code for the index.php, the jquery and the slideshow0.html
index.php
<body>
<div class="main">
<div class="contenedorHeader">
<?php include("header.html"); ?>
</div>
<div class="central">
<div class="fondoDescription">
<div id="contenedorDescription"></div>
</div>
<div id="slideshowHolder"></div>
</div>
<div class="footer"></div>
</div>
</body>
jquery code:
$(document).ready(function()
{
$("#slideshowHolder").load("slideshow0.html");
});
slideshow0.html:
<script type="text/javascript">
function slideSwitch() {
var $active = $('#slideshowContent IMG.active');
if ( $active.length == 0 ) $active = $('#slideshowContent IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshowContent IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>
</head>
<body>
<div id="slideshowContent">
<img src="images/slideshows/home/image1.png" alt="Slideshow Image 1" class="active"/>
<img src="images/slideshows/home/image2.png" alt="Slideshow Image 2" />
<img src="images/slideshows/home/image3.png" alt="Slideshow Image 3" />
</div>
</body>
</html>
As you can see, the slideshow0.html is loaded into "slideshowHolder". There's no problem here, but when I click an item in the menu I need to replace "slideshow0.html with another slide-show which is exactly like this one except for the images, and the problem is that the looping interval doesn't works properly, it's like a function is executing twice, or something like that. I've tested the slide-show outside the PHP and they works fine, so I'm guessing is a problem with the PHP or the method to load/replace the HTML.
You can see the project here: http://www.spamtv.com.ar/coya/index.php The first slide-show is slideshow0.html, click in "web" to load the next slide-show (which doesn't works)
When you load/replace the slideshow, the old interval defined by setInterval( "slideSwitch()", 5000 ); is still set and running. Each time you load a new slideshow, a new interval will be defined but the old ones won't be deleted.
You have to manually stop them:
$(document).ready(function()
{
if (slideshowInterval) {
clearInterval(slideshowInterval);
}
$("#slideshowHolder").load("slideshow0.html");
});
And when defining it:
$(function() {
slideshowInterval = setInterval( "slideSwitch()", 5000 );
});

Loading Content using Ajax with PHP Include

I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.

Categories