Jquery Hide Function in PHP - php

I have a while statement that is echoing about 10 different stories. Every story has a user comment. When clicking the button edit I want one of the functions to hide the user comment. Here is the code I wrote to try and make it happen. Let me know if you think of why this wouldn't work.
<script>
$(".edit_<?php echo $story_id ?>").click(function () {
$(".comment_<?php echo $story_id ?>").hide("fast");
});
</script>
<?php
if (!empty($user_comment))
echo "
<p class='user_comment comment_$story_id'><strong>$user_comment</strong> <a class='edit_story_comment edit_$story_id'>Edit</a></p>";
else
echo "<p id='user_comment_$story_id'><span id='edit_no_story_comment'>Edit</span></p>";
?>

so im gonna ges its becuse of the ankertag is being defined after you are
hocking upp the event with jquery
use jquerys on load event to get around this
$(function() {
$(".edit_<?php echo $story_id ?>").click(function () {
$(".comment_<?php echo $story_id ?>").hide("fast");
});
});
hope this help
(mixing php html and jquery and string concatenation is beautiful btw :D)

Related

Integrating JQuery into php file

I am trying to tweak a website so users will be able to swipe through the photo galleries on their mobile devices. I tried doing this by using JQuery. The website was not written by me, so I can't really explain the choices the previous programmer made regarding their code.
Currently, users can change pictures by clicking (tapping) on the current picture. The code for this is found in a php file called home.php. This is it:
<?php
...
$main_content .= "\n <div class='main_image'>
<a href='$next_slideURL' style='display:block'>
<img src='$root/$item_path/$slideFile' alt='$slideCaption from $projectTitle\n [xxxxxxxxxxxxx]' style='max-width:832px; max-height:500px' title='$projectTitle: $slideCaption. \nclick for next slide ($next_slideCaption). '></a>
</div>\n";
...
?>
To add swiping capabilities, I added the following code right after the one above:
echo "<script type='text/javascript'>";
echo "(function(){
$(\"div.main_image\").on(\"swipeleft\", swipeleftHandler);
$(\"div.main_image\").on(\"swiperight\", swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage(\"$next_slideURL\", {transition: \"slideleft\", changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage(\"$previous_slideURL\", {transition: \"slideright\", changeHash: false});
}
});";
echo "</script>";
While I'm not sure exactly why this isn't working, I have a few possible reasons (which might all be true unfortunately).
1) Since the div class='main_image' is done as a variable declaration, the JQuery line "div.main_image" doesn't have a reference (i.e. it doesn't know what main_image is). I'm not sure why the div is created as a variable declaration ($main_content keeps being added on throughout the php file, and in the end it's echoed along with a bunch of other variables).
2) I need to include the following code for JQuery but I have it in the wrong place:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
right now I have it in the header section of index.html file. Is this wrong?
3) I've never used JQuery before, so any number of things might be wrong about the short script I wrote.
Sorry about the long post, I'm not sure how to explain this in a simpler way.
I'd appreciate it if anyone could help me either with this approach, or propose a different one.
Cheers!
Use $ while writting ready function
<?php
echo "$(function(){
// ---^--- use $ here
....
....";
echo "</script>";
?>
If $ conflicts then your can use jQuery like,
Full Code:
<?php
echo "<script type='text/javascript'>";
echo "jQuery(function(){
jQuery('div.main_image').on('swipeleft', swipeleftHandler);
jQuery('div.main_image').on('swiperight', swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage('".$next_slideURL."', {transition: 'slideleft', changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage('".$previous_slideURL."', {transition: 'slideright', changeHash: false});
}
});";
echo "</script>";
?>
Looks like you need to put your javascript in the $main_content variable, like the other code.
But to be honest you should seperate your javascript from the html/php.
Best way is to break out of php tags
and change this (function () to $(function ()
<?php
//php code
?>
<script type='text/javascript'>
$(function () {
$("div.main_image").on("swipeleft", swipeleftHandler);
$("div.main_image").on("swiperight", swiperightHandler);
function swipeleftHandler(event) {
$.mobile.changePage("$next_slideURL", {
transition: "slideleft",
changeHash: false
});
}
function swiperightHandler(event) {
$.mobile.changePage("$previous_slideURL", {
transition: "slideright",
changeHash: false
});
}
});
</script>;
<?php
//php code
?>

get value from a link without clicking it?

I am trying to show a jQuery alert by hovering on different links with different ids.
I want to tailor the alert based on each link hovered over. These links are created dynamically from a table...
Each link has a different id attribute, so I was thinking to have alert for each without having to click on the link.
For example: a link might have index.php?id=1 So I want to show an alert on hover that says This is an alert for link 1, etc.
Edit 1:
The div:
echo '<div class="trigger">';
echo "<a class='trigger' href='".INDEX.'?categ='.$_GET['categ'].'&action='.$_GET['action'].'&subaction=viewlevels'.'&levelid='.$compi['Competence_ID']."'>";
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("What is this?").'"/></a>';
echo '<div id="pop-up">';
echo" <h3>Pop-up div Successfully Displayed for".$_GET['levelid'].
"</p></div>";
Edit 2:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$('.trigger').mouseover(function() {
alert("You are hovering over " + $(this).attr('href').match(/id=([0-9]+)/)[1]);
});
</script>
But it always tells me that levelid is undefined..( of course because the form has not been sent)
Yes, you can use jQuery's mouseover() for this:
$('.trigger').mouseover(function() {
alert("This is an alert for link " + $(this).attr('href').match(/id=([0-9]+)/)[1]);
});
You should change from using ID's to using a common class.
to bind jquery function on a link over of container child element use below code
$(document).ready(function(){
jQuery("#container a").each(function() {
jQuery(this).mouseover(function() {
alert(jQuery(this).attr('href'));
});
});
});
$('#aid').mouseover(function(){alert('whatever you want'+this.id)});
documentation http://api.jquery.com/mouseover/
You can also use .hover and that has two callback one when hover-over and one for hover-out.
$('a').hover(function(){
alert($(this).attr('href'));
},function(){
alert('hover out');
});
If you are creating links dynamically, then associate attribute class (say sampleclass) and attribute id as (concatenate "link " and id value from database) with each link
Now
$(document).redy(function(){
$(".sampleclass").hover(function(){
alert("This is " + $(this).attr("id"));
});
});

Calling a javascript function by using onClick in a hyperlink

I have been looking online, but I have failed to find a direct answer to my question:
Can you use onClick for a tags?
In other words can you do this (note echoed through php)?
echo "\n";
I tried to run this, but when I click on the link, my counter function is not being called.
The rest of my code snippet:
echo "<script type=\"text/javascript\" src=\"src\jquery\jquery.js\">\n";
echo "function counter(){\n";
echo "alert(\"HELLO WORLD!\");\n";
echo "}\n";
echo "</script>\n";
echo "\n";
Although that should work, it's better practice not to bind events inline. I would suggest looking into addEventListener and for older versions of IE, attachEvent. More information on these can be found in a topic here: Correct usage of addEventListener() / attachEvent()?
If you wait for the window to be ready, you ensure that the element is on the page and defined for you to access it.
window.onload = function(){
//add any event listeners using the above methods in here
}
Example:
<script>
window.onload = function(){
var t = document.getElementById("test");
t.addEventListener("click", sayHi, false);
function sayHi(){
alert("Hi");
}
}
</script>
<div id="test">test</div>​
According to your above echo statements, if you are determined to make it work that way then you can try this:
echo "<script type='text/javascript' src='src/jquery/jquery.js'></script>\n";
echo "<script>\n"
echo "function counter(){\n";
echo "alert('HELLO WORLD!');\n";
echo "}\n";
echo "</script>\n";
echo "<a href='#' id ='loginbutton' onClick='counter()'></a>\n";
notice that I closed the script tag including jQuery and added a new opening tag right below it.
EDIT:
Script tags that reference external resources (via the src attribute)
are no longer able to execute script embedded within the tag itself.
Read more here
Made a little Demo code, Note that the function fires and then the href is followed. You can turn this off with JS by returning false.
<script type="text/javascript">
function counter() {
alert("do something here")
var FollowHref_Or_Not = false;
// true would simply follow the href after the function is activated
return FollowHref_Or_Not;
}
</script>
Test Link
To add more context to the comments above, here's a working example. Where I put the HTML comment about simulating an echo, just put your PHP echo line. Also note that I added a return false; This prevents the default link click behavior from executing. Since your href is "#" it would modify your URL to put "#" in the URL so if you used your browser back button you'd still be "stuck" on the same page.
http://jsfiddle.net/6pEbJ/
<html>
<head>
<script type="text/javascript">
function connect()
{
alert('connected!');
}
</script>
</head>
<body>
<!-- simulated echo result here -->
Testing
</body>
</html>

How do I run a function only when a div gets loaded?

I want to run a function only when a div gets loaded.
When I load the page, a number of files are loaded. At the end of the list, PHP echoes a div. When this one is displayed, jQuery should run a function.
I can do this with a click-event, but I want it to work automatically, without pushing a button.
This is how it works with a click:
$("#PP_end_show").live("click",function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
This is the div echoed by PHP:
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
The output is generated after an AJAX call:
<form id="PP_search_input" method="post" name="search_ID" ONSubmit="xmlhttpPost('PP_search_stream_client.php', 'PP_search_input', 'PP_thumb_output', '<img src=\'images/wait.gif\'>');return false; ">
<input name="search_string" type="text" class="PP_input" id="search_string" value="<?php echo $_POST['search_string']; ?>"/>
<button type="submit" class="PP_submit" id="search_submit"> search </button>
at the end of the generated output the specific div will be printed and should trigger the new jQuery function.
This is how I would tackle this issue, assuming I've understood it correctly in which the submission of the form PP_search_input, returns the html needed, in which then a the javascript code should be executed.
$('#PP_search_input').submit(function() {
$.ajax({
url: 'PP_search_stream_client.php',
type: 'post',
data: $(this).serialize(),
success: function(html) {
$(html).insertAfter('#whereToInsert') //change to however you want to insert the html
.find("#PP_head_bar").slideToggle("slow").end()
.find("#PP_info_file_wrap").slideUp("slow");
}
});
});
Try putting your javascript code inside the generated ajax code.
For example if your ajax is generated from the php code
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
then try smth like this
<?php
echo "<div id=\"PP_end_show\"></div>";
echo '$(function(){$("#PP_head_bar").slideToggle("slow");';
echo '$("#PP_info_file_wrap").slideUp("slow");});';
?>
You could use the livequery plugin
You would then use it as follows :
$('#PP_end_show').livequery(function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
The code in the function would execute when the element in the selector (#PP_end_show) was added to the DOM
Why not echo your javascript along with the DIV code?
You can use PHP to echo Javascript like this:
After your code:
<?php echo "<div id=\"PP_end_show\"></div>"; ?>
Write this:
echo "<script type='text/javascript'>
$('#PP_head_bar').slideToggle('slow');
$('#PP_info_file_wrap').slideUp('slow');
";
echo "</script>";
This should work.
In your JS, wrap the code you want to execute in a function. i.e.
function showInfoBlock() {
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}
In your PHP, write out the JS needed to call that function after writing out the PP_end_show div. i.e.
<?php echo "<div id=\"PP_end_show\"></div><script>$(function() { showInfoBlock(); })();</script>"; ?>
This does what you are asking:
(function($){
var checkForEndInterval = window.setInterval(function(){
if ($('#PP_end_show').length) {
// stop interval
window.clearInterval(checkForEndInvertal);
// call your code now
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}
},200);
})(jQuery);
However this is not a good idea because its silly and what you are asking for hints you not understanding but that is why you are here. Since you already know when your AJAX is called, call it explicitly and attach a success handler to it.
$.ajax({
/* your other setup code here */
success : function(data) {
// run your code
}
});
If you were not doing AJAX as you say, I would put a script tag at the end of your output and have it call your code as the simplest approach. Even still, you could use the jQuery.load method (not event) which by default executes JavaScript from your response.
Happy coding.
keep that jquery live-click-function as it is
& run the below code in php
<?php
echo "<div id=\"PP_end_show\"></div>";
echo "$(function(){ $(\"#PP_end_show\").click(); });";
?>
$.ready(function(){
$("#wrapper").add("div").attr('id','PP_end_show');
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
<div id='wrapper'>
</div>
Bind the live event to a custom event that is triggered by the document:
$(document).trigger('echo');
$("#PP_end_show").live("echo", function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
});
References
jQuery API: .trigger()
JQuery API: .live()
Jason Brumwell enter right answer, also you can use the $.when function of JQuery.
http://api.jquery.com/jQuery.when/
If the action you want to perform once the desired div loads is bound to a click event, simply trigger click at the end of the ajax request something like:
$.ajax({
url:'whatever.php',
type:'post', //guessing obviously
success: function(data){
$('#PP_end_show').click(); //etc
}
});
These guys are right though, you are doing this all backwards mate
Does it have to be that exact div? It seems to me that you should just execute the function on load of the document. That way you know all your elements are loaded.
$(function()
{
// This function is executed when the DOM is ready, including that last div.
// Could be that images are still loading, but your code usually won't depend on that.
}
Try this,
if(window.isBodyLoaded){
try{
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}catch(d){
alert(d)
}
}
Use a callback function.
Its a function that will be triggered as soon as your event is handled.
so for Jquery:
$("#PP_end_show").live("click",function(){
$("#PP_head_bar").slideToggle("slow");
$("#PP_info_file_wrap").slideUp("slow");
}, myCallback());
function myCallback(){
//Do what ever you want to happen after
//the div creationin this function
}
And I think that should do the trick

Help with jquery tabs

I need to know how to link (via a regular href anchor on a different page) to content that is inside a tab that is not the default tab. Can this be done? My code will explain hopefully what I require:
My Code:
The following is my profile_edit.php page:
The javascript:
<script src="Javascript/jquery-1.4.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
var tabContainers = $('div.tabs > div');
tabContainers.hide().filter(':first').show();
$('div.tabs ul.tabNavigation a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
$('div.tabs ul.tabNavigation a').removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(':first').click();
});
$(function () {
var tabs = [];
var tabContainers = [];
$('ul.tabs a').each(function () {
// note that this only compares the pathname, not the entire url
// which actually may be required for a more terse solution.
if (this.pathname == window.location.pathname) {
tabs.push(this);
tabContainers.push($(this.hash).get(0));
}
});
// sniff for hash in url, and create filter search
var selected = window.location.hash ? '[hash=' + window.location.hash + ']' : ':first';
$(tabs).click(function () {
// hide all tabs
$(tabContainers).hide().filter(this.hash).show();
// set up the selected class
$(tabs).removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(selected).click();
});
</script>
The html and PHP (a portion):
<div class="tabs">
<ul class="tabNavigation">
<li>Account</li>
<li>Password</li>
<li>Favorites</li>
<li>Avatar</li>
</ul>
<div id="account_div">
<?php include("personal_info_edit.php"); ?>
</div>
<div id="change_password_div">
<?php include("change_password.php"); ?>
</div>
<div id="favorites_div">
<?php include("favorites.php"); ?>
</div>
<div id="avatar_div">
<?php include("avatar.php"); ?>
</div>
</div>
The following is contained in my change_password_submit.php page:
$update_pass= ("Password changed successfully.");
header("location:profile_edit.php?update_pass=$update_pass#change_password_div");
exit();
By default, whenever profile_edit.php is loaded, the personal_info_edit div is shown and the others are hidden. What do I need to change in the code so that I can reference the 2nd div (ie. change_password div and hide the rest after someone changes their password?
Any help will be greatly appreciated.
This is perhaps not the most elegant solution, but it should work.
You can have PHP sniff your url variables for the existence of a particular variable. I'd probably call this something like 'selectedTabId' or something like that. Then, if that variable exists, you can have jQuery invoke the click action on that tab. You'll want to use switch/case for this rather than just sending through whatever happens to be in the URL, as people can put nasty things there that you don't want your jQuery to run. I won't do that in my example below, for expediency's sake.
This is a notional example...
<?php
if( array_key_exists('selectedTabId',$_GET) ){
$selectedTabId = $_GET['selectedTabId'];
echo "<script type=\"text/javascript\">";
echo "jQuery(document).ready(function(){'#$selectedTabId').click()});";
echo "</script>";
}
?>
Give that a shot and see if it works for you.
I use this thinger: http://flowplayer.org/tools/tabs/index.html
It does that for you. It also does a whole lot on top. It maybe worth implementing instead of your custom solution?
Here's an example of it in action: http://www.estanciaboerne.com/amenities#TAB2entertainment
(This doesn't actually teach you anything, but it is a solution to your problem, so I'm sorry and you're welcome all in one.)

Categories