I have this code on my website and this div appears when u successfully post a comment.
Now I want the div element disappear after 3-5 seconds. Here's my code:
echo "<div class='granted'><p>Comment posted.</p></div>";
echo "<script type=\"text/javascript\">
setTimeout(function() {
$('.granted').fadeOut('fast');
}, 3000);
</script>";
Thanks!
Your code works perfectly. I think you have missed to link the script library.
Adding this line before the PHP script does the trick.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Your code should work perfectly. You can also use the delay() function:
$('.granted').delay(3000).fadeOut('fast');
$(document).ready(function(){
setTimeout(function(){
$('.granted').hide();}, 5000);
});
It's not good practice to include HTML tags inside php codes.
<div class='granted'><p>Comment posted.</p></div>
<script>
$(function(){
setInterval(function(){
$('.granted').fadeOut(1);
},5000);
});
</script>
Related
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
?>
$("#bt-potrdi").click( function(e) {
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
when i click on button this jquery code is executed and works fine. Can i execute this code without click event?
I want to execute this code from php when some data is executed successfully like for example
if ($ok) {
?>
//execude ajax code
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
<?php
}
is this possible? PHP is server side code so i didn't find any good example if this is possible
Similar to the other suggestions, but this doesn't rely on having 2 copies of the same code...
if ($ok) {
?>
<script type="text/javascript">
$(function() {
$("#bt-potrdi").trigger("click");
});
</script>
<?php
If you ever change the click event handler, this will still work. This means that you won't need to make any future changes in 2 places.
If I understand the question, you want to execute some javascript on page load if $ok is true. To do that, you should be able to do something like:
if ($ok) {
?>
<script type="text/javascript">
//execute ajax code
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
EDIT: Also, e.stopPropagation(); is not going to work because e is not defined anywhere.
What happens is when your PHP script is executed, if $ok evaluates to true, then your jquery code is included in the generated document, and is omitted if it doesn't. But at this point, there is no event, so the following line will not work.
e.stopPropagation();
However, as jdwire suggested, you can wrap your javascript in a script tag, and have it executed that way, without being triggered by an event. So... like this:
<?php
if ($ok) {
?>
<script type="text/javascript">
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
?>
I would design my code so that i could add classes and set z-indexes straight up when html is rendered, but if you want to do those with jquery, jsut wrap them in <script> and $(document).ready(function({}); so they will be executed when dom is ready.
eg.
if ($ok) {
?>
//execude ajax code
<script>
$(document).ready(function{
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
</Script>
<?php
}
edit
Okay i assumed e.stopPropagation(); is set somewhere before since it was in questions example aswell. removed it for now.
You can echo out the code in <script/> tags and it will be run as JavaScript, or with the code you have, just place it between tags and it should be fine :)
But you cannot do this "live". Only when the page is requested ONCE.
You can also do it this way to pass PHP variables over to javaScript. I think it's a lot cleaner.
$check = 1;
?>
...
<script type="text/javascript">
var check = <?= $check; ?>;
...
if (check)
{
$("#bt-potrdi").trigger("click");
}
I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn't refresh?
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
$('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');
});
});
</script>
It's because you're using PHP to generate the random number, and it can't possibly be refreshed across calls to the JS function -- it's embedded in the HTML by that point.
May be you can also use live like instead of click
$(document).ready(function(){
$('#btn-get-random-image').live("click", function () {
// your works here
}
});
also check out jquery live
As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!
Edit: modified code to make it suck less.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var myPics = <?php echo json_encode($pics); ?>;
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
var index;
do {
index = Math.floor(Math.random() * myPics.length);
} while ( typeof myPics[index] == 'undefined' );
$('#my-img')
.attr('src', myPics[index]);
});
});
</script>
This uses PHP's JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The do/while loop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.
Your PHP is creating JS code, which gets sent to the browser once when the page is rendered. Each call to the JS function runs the function as it existed when the page was rendered.
I am just trying to test a simple ajax call on my server using jquery
I have a HTML file like this
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#connect_button").click(function(event){
$("#placeholder").load("http://mysever/AjaxResponse.php");
})
});
</script>
</head>
<body>
<button id="connect_button" type="button">Connect</button>
<span id="placeholder">This has not worked</span>
</body>
</html>
AjaxResponse.php, which works when accessed from the browser statically, looks like this
<?php
echo "This now works";
?>
The code runs and the replace happens the only problem is that the page returns a blank string causing the span to be empty
If I change the code to use another jQuery call such as $.get() the callback is sent back the textStatus of "Success" and a data value of ""
What am I missing here? Do severs need to be set up to respond to Ajax calls. Am I misusing jquery?
Is your AjaxResponse.php on the same domain? Ajax calls won't work cross-site.
If you want, you could check if the loaded page has anything in it like this:
$(function(){
$('#connect_button').live('click', function(){
content = $.get('test.php',function(data){
content = data;
if (content != ""){
$('#placeholder').html(content);
}else{
$('#placeholder').html('This has not worked');
}
});
});
})
That way if the returned data is empty, it will put "This has not worked" in the placeholder id.
php sends html strings to html via ajax wrapped in <p class="select"></p> tags, css reads class perfectly. javascript/jquery does not. javascript/jquery wont even parse <p onclick="function()"></p>. What am i doing wrong?
heres my php (sends data via ajax fine)
echo "<p class='select' onclick='populate();' >{$row['song_name']} </p>";
heres my css (works fine)
p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}
heres my javascript
method 1 jquery.
$("p .select").click(function(){
var str = $(this).val();
alert(str);
});
method 2 onclick function.
function populate()
{
alert('here')
}
neither of the two methods respond at all. Guru why is this?
$("p .select").live ( "click" , function(){
var str = $(this).text();
alert(str);
});
See
Events/live
Binds a handler to an event (like
click) for all current - and future -
matched element.
Two things:
p .select will choose <p> tags containing an element with class select. p.select selects <p class="select">.
Why not move the populate function to within the live? I suspect the jquery live (or click) removes any explicit handlers.
Try this:
$("p.select").live("click",function()
{
var str = $(this).text();
alert(str);
populate();
});
I posted a working(in Firefox) example below. I think you forgot to put the jquery method inside the onload event. Beside the other (small) bugs...
<html>
<head>
<style>
p.select{color:#fff;padding: 5px;margin:0}
p.select:hover{color:#fff;background:#f60;cursor:pointer;}
</style>
<script src="jquery-1.3.2.min(2).js" type="text/javascript"></script>
<script type="text/javascript">
function bodyOnLoad() {
//instead of "p .select" "p.select"
$("p.select").click(
function(){
//changed val() into text()
var str = $(this).text();
alert(str);
});
}
</script>
</head>
<body onload="bodyOnLoad()">
<p class='select'>Songname</p>
</body>
</html>