displaying a series of youtube embeds that can be hidden/displayed - php
My goal is to show a series of embedded youtube videos on one page but allowing the user to hide or show any youtube video by clicking a button associated with a specific youtube video on the page. I made a form that submits the youtube embed code to a mysql database and I created a php file to retrieve every embed code using a for loop. For each iteration of the for loop, a youtube video will pop up with a corresponding button which will allow the user to hide or show the youtube video.
It works when there is only one entry in the mysql table but does not work when more youtube embed codes are uploaded. For example, when there are two youtube embed codes uploaded, two buttons are created, but when I click either of the two buttons, it will only show or hide the first youtube embed. None of the buttons will show the second youtube video.
here is the code with some edits:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>hide/show iframe</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<style type="text/css">
<!--
#frDocViewer {
width:70%;
height:50%;
display:none;
}
-->
</style>
<script type="text/javascript">
<!--
function HideFrame() {
var fr = document.getElementById ("frDocViewer");
if(fr.style.display=="block") {
fr.style.display="none";
} else {
fr.style.display="block";
}
}
//-->
</script>
</head>
<body>
<?php
mysql_connect ("","","") or die(mysql_error());
mysql_select_db ("") or die(mysql_error());
$lastid = mysql_query ("SELECT * FROM embed ORDER BY id DESC LIMIT 1");
$lastid = mysql_fetch_assoc($lastid);
$lastid = $lastid['id'];
for ($count=1; $count<= $lastid ; $count++) {
$iframe = mysql_query ("SELECT * FROM embed WHERE id=$count ");
$iframe = mysql_fetch_assoc($iframe);
$iframe = $iframe['url'];
echo "
<image src='utube.gif' onclick='HideFrame()' />
<div id='frDocViewer'>
$iframe
</div>
";
}
?>
</body>
</html>
Because each div has the same ID. You need to create unique ID's for each DIV to show or hide ie. frDocViewer1, frDocViewer2 etc
Use your $count variable to echo it's value onto the ID as it will increment by 1 for each iteration of the loop.
echo "
<image src='utube.gif' onclick='HideFrame()' />
<div id='frDocViewer_{$count}'>
$iframe
</div>
";
Then you just need to make sure that you have corresponding Javascript for each of those DIV's. I would send the id into the javascript function using your onclick tag.
for ($count=1; $count<= $lastid ; $count++) {
$iframe = mysql_query ("SELECT * FROM embed WHERE id=$count ");
$iframe = mysql_fetch_assoc($iframe);
$iframe = $iframe['url'];
echo "
<image src='utube.gif' onclick='HideFrame({$count})' />
<div id='frDocViewer_{$count}' class='frDocViewer'>
$iframe
</div>
";
}
And then have the javascript code as something like:
var old_element = null;
function HideFrame(id) {
var fr = document.getElementById("frDocViewer_" + id);
if(fr != old_element)
{
fr.style.display = "block"
if(old_element != null) old_element.style.display = "hide";
old_element = fr;
}
}
Then finally you need to change your CSS to make frDocViewer a class rather than a unique style. Notice above in the PHP echo string I added in the new class attribute to the DIV
<style type="text/css">
.frDocViewer {
width:70%;
height:50%;
display:none;
}
</style>
PS: This code might not actually compile, it's just a rough guide.
I think the problem is with this line:
<div id='frDocViewer'>
IDs are supposed to be unique across the entire page, but you're creating a new element with the same ID on each iteration of your loop. I haven't tested this, but my assumption is that when your JavaScript executes to hide/show that ID, it's only picking up the first ID by that name that it finds.
You'll need to change your code to give a unique ID to each iteration, and pass a reference to that element when you call your HideFrame() function. The function can then operate on that specific ID.
hmm...where to start....
if you getElementById where your id is frDocViewer AND frDocViewer is used by every video there will be problems.
how about something like
<div onclick='HideFrame(this)' >
<image src='utube.gif'/>
....
</div>
function HideFrame(el) {
...
}
Not at all tested, but you NEED to go for something more GENERIC then hard coding an id....in my opinion
Related
How to use php dom document to remove and replace tags
I have image tag <img src="path_to_file.png"> but I want that the image tag be converted to link in mobile site. So I want img to be converted to an href: Click here to open in new tab I am getting started with php dom. I could get all the attribute listed. $newdocument = new DOMDocument(); $newdocument->loadHTML(); $getimagetag = $doc->getElementsByTagName('img'); foreach($getimagetag as $tag) { echo $src=$tag->getAttribute('src'); } But how do we get the src attribute , then remove the img tag completely because it contains other parameter like height and length and then create new tag of link? Hi guys I could get it done from php dom using following code $input="<img src='path_to_file.png' height='50'>"; $doc = new DOMDocument(); $doc->loadHTML($input); $imageTags = $doc->getElementsByTagName('img'); foreach($imageTags as $tag) { $src=$tag->getAttribute('src'); $a=$doc->createElement('a','click here to open in new tab'); $a->setAttribute('href',$src); $a->setAttribute('style','color:red;'); $tag->parentNode->replaceChild($a,$tag); } $input=$doc->saveHTML(); echo $input; The create element can also be used to put text between <a></a> ie Click...new tab. replacechild is used to remove $tag i.e. img and replace it with a tag. By setting attribute, we can add other parameters like style,target etc. I used php dom in the end because I only wanted the data that I get from mysql to be converted and not the other elements like logo of website. Ofcourse it can be possible using javascript too. Thanks #dave chen for javascript way and pointing to detecting mobile link. #nate for pointing me to a answer.
Use phpQuery, it's amazing. It's just like using jquery! :) https://code.google.com/p/phpquery/
I would recommend doing this with JavaScript: <!DOCTYPE html> <html> <head> <title>Images Test</title> <script> window.onload = changeImages; function changeImages() { var images = document.getElementsByTagName("img"); while (images.length > 0) { var imageLink = document.createElement("a"); imageLink.href = images[0].src; imageLink.innerHTML = "Click here to view " + images[0].title; images[0].parentNode.replaceChild(imageLink, images[0]); } } </script> </head> <body> Here is a image of flowers : <img src="images/flowers.bmp" title="Flowers" ><br> Here is a image of lakes : <img src="images/lakes.bmp" title="Lakes" ><br> Here is a image of computers: <img src="images/computers.bmp" title="Computers"><br> </body> </html> Example
How can I display a random image from a php array using jQuery?
I have been trying to create a random picture display animation, in the style of a slot machine wheel. The user clicks 'spin' and a gif image appears, giving the effect of a slot wheel spinning. When the wheel stops, the spinning effect gif image is replaced by a random member's picture. However, the random member's picture is not appearing. In firebug, I can see that the array is being populated correctly, and the member pictures (with correct url) are all present. The issue seems to be that the jQuery script is not prepending the tag to the in which the image is to appear, and I cannot work out why. The PHP to gather the information for the array is here: $q = "SELECT id, username FROM members WHERE my_sex =:req_sex"; $stmt = $dbo->prepare($q); $stmt->execute(array(":req_sex" => $req_sex)); while($r = $stmt->fetch()) { $m_id = $r['id']; $m_name = $r['username']; $m_pic .= '"members/'.$m_id.'/minis/resized_image_'.$m_id.'_0.jpg", '; } $m_pic = rtrim($m_pic, ', '); and the jQuery which I am sure is incorrect somewhere is here: $(document).ready(function(){ images = new Array(<?php echo $m_pic; ?>); var length = images.length; var which = Math.round(Math.random()*(length-1)); $('<img src="'+images[which]+'" alt="" class="randomMember"/>').prependTo('div#wheel'); }; I have been playing around with this and tried various methods, and using firebug to investigate, the best I have managed to achieve is to get the following line showing in the html. <img class="randomMember" alt="" src="" /> I cannot remember how I did this, but I think it was using document.write and not wrapping it in a function. I have only been using javascript and jQuery for a week or so, and despite a whole lot of Googling and reading up, I cannot see why this isn't working out. Thanks in advance! EDIT: the html is as follows: <div class="hidden_sidebox"> <div id="chat_view"> <div id="wheel"> <img src="members/0/default_pic.jpg" alt="" class="preSpin" /> <img src="images/randomChatWheel.gif" alt="" class="spinAnimation" style="top: -220px;" /> </div> //here is where the problem jQuery script is...I think this is the correct place for it, as it will prependTo the previous div element (which I have explicitly specified anyway, just in case) <div id="btnPanel"> <div id="chatButton">CHAT</div> <div id="spinButton">SPIN</div> </div> <div id="chatSplash"></div> </div> </div> and the function for the wheel spin (which works perfectly apart from the final image failing to display) is here: $(document).ready(function() { $("div#chatSplash").click(function () { $("div#chatSplash").slideUp("fast"); $('img.randomMember').hide(); $('img.spinAnimation').hide(); $('div#spinButton').removeClass('ButtonDisabled'); $('div#chatButton').removeClass('ButtonDisabled'); }); $("div#spinButton").click(function () { $("img.preSpin").hide(); $("img.spinAnimation").show(); $('div#spinButton').addClass('ButtonDisabled'); $('div#chatButton').addClass('ButtonDisabled'); setTimeout(function(){$("img.spinAnimation").hide(); $('img.randomMember').show(); $('div#spinButton').removeClass('ButtonDisabled'); $('div#chatButton').removeClass('ButtonDisabled'); }, 2500); }); });
There is a simple error here, you're not closing parentheses. You have: $(document).ready(function(){ . . .}; Which should be $(document).ready(function(){ . . .});
Try this in PHP: $pictures = array(); while($r = $stmt->fetch()) { $pictures[] = sprintf('members/%d/minis/resized_image_%d_0.jpg', $r['id'], $r['id']); } and then in JS: images = <?php json_encode($pictures); ?>;
Echoing out JavaScript with nested quotes from a PHP script onto an HTML page?
I've been trying for about two hours to get the following code stored in a PHP string and then echoed out as JavaScript on a webpage: <div id="reply-box" style="display: block; width:100%;float:right;"> <script type="text/javascript" src="http://example.com/public/js/3rd_party/ckeditor/ckeditor.js"></script> <script type="text/javascript"> /* Dynamic items */ CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]","switch_option":"0","menu_option_text":"Enter the description for this acronym (EG: Laugh Out Loud)","menu_content_text":"Enter the acronym (EG: lol)","single_tag":"0","optional_option":"0","image":""},"ads1":{"id":"46","title":"ads1","desc":"","tag":"ads1","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"background":{"id":"27","title":"Background-color","desc":"Adds a background color behind the text","tag":"background","useoption":"1","example":"[background=red]Red background behind this text[/background]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"entry":{"id":"35","title":"Blog Entry Link","desc":"This tag provides an easy way to link to a blog entry.","tag":"entry","useoption":"1","example":"[entry=100]Click me![/entry]","switch_option":"0","menu_option_text":"Entry ID","menu_content_text":"Text to display","single_tag":"0","optional_option":"0","image":""},"blog":{"id":"34","title":"Blog Link","desc":"This tag provides an easy way to link to a blog.","tag":"blog","useoption":"1","example":"[blog=100]Click me![/blog]","switch_option":"0","menu_option_text":"Blog ID","menu_content_text":"Text to display","single_tag":"0","optional_option":"0","image":""},"code":{"id":"13","title":"Code","desc":"Allows you to enter general code","tag":"code","useoption":"0","example":"[code]$text = 'Some long code here';[/code]","switch_option":"0","menu_option_text":"","menu_content_text":"Code","single_tag":"0","optional_option":"0","image":""},"extract":{"id":"33","title":"Extract Blog Entry","desc":"This will allow users to define an extract for an entry. Only this piece of the entry will be displayed on the main blog page and will show up in the RSS feed.","tag":"extract","useoption":"0","example":"[extract]This is an example![/extract]","switch_option":"0","menu_option_text":"","menu_content_text":"Blog entry extract","single_tag":"0","optional_option":"0","image":""},"hr":{"id":"12","title":"Horizontal Rule","desc":"Adds a horizontal rule to separate text","tag":"hr","useoption":"0","example":"[hr]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"html":{"id":"15","title":"HTML Code","desc":"Allows you to enter formatted/syntax-highlighted HTML code","tag":"html","useoption":"0","example":"[html]<div class='outer'>\n <p>Hello World</p>\n </div>[/html]","switch_option":"0","menu_option_text":"","menu_content_text":"HTML Code","single_tag":"0","optional_option":"0","image":""},"imgr":{"id":"39","title":"Image","desc":"Displays linked images, floating to the right","tag":"imgr","useoption":"0","example":"[imgr]http://www.google.com/intl/en_ALL/images/logo.gif[/imgr]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"jump":{"id":"45","title":"jump","desc":"","tag":"jump","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"media":{"id":"32","title":"Media","desc":"Allows a user to post media content from certain common media sites","tag":"media","useoption":"1","example":"[media]http://www.youtube.com/watch?v=YqqLx-2vUr0[/media]","switch_option":"0","menu_option_text":"Dimensions (Flash Only)","menu_content_text":"Media URL","single_tag":"0","optional_option":"1","image":""},"member":{"id":"31","title":"Member","desc":"Given a member name, a link is automatically generated to the member's profile","tag":"member","useoption":"1","example":"[member=admin] runs this site.","switch_option":"0","menu_option_text":"Member Name","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"page":{"id":"38","title":"Multi-Page Articles","desc":"This tag can be used to create multi-page articles. Page links are automatically added based on the number of times this tag is used, and the content is hidden until you reach the specified \"page\".","tag":"page","useoption":"0","example":"Content 1\n[page]\nContent 2\n[page]\nContent 3","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"overline":{"id":"42","title":"Overlined Text","desc":"Makes the text overlined","tag":"overline","useoption":"0","example":"[overline]This text is underlined[/overline]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"php":{"id":"14","title":"PHP Code","desc":"Allows you to enter PHP code into a formatted/highlighted syntax box","tag":"php","useoption":"0","example":"[php]$variable = true;\n\nprint_r($variable);[/php]","switch_option":"0","menu_option_text":"","menu_content_text":"PHP Code","single_tag":"0","optional_option":"0","image":""},"post":{"id":"6","title":"Post Link","desc":"This tag provides an easy way to link to a post.","tag":"post","useoption":"1","example":"[post=1]Click me![/post]","switch_option":"0","menu_option_text":"Enter the Post ID","menu_content_text":"Enter the title for this link","single_tag":"0","optional_option":"0","image":""},"pre":{"id":"43","title":"pre","desc":"","tag":"pre","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"spoiler":{"id":"7","title":"Spoiler","desc":"Spoiler tag","tag":"spoiler","useoption":"0","example":"[spoiler]Some hidden text[/spoiler]","switch_option":"0","menu_option_text":"","menu_content_text":"Enter the text to be masked","single_tag":"0","optional_option":"0","image":""},"sql":{"id":"16","title":"SQL Code","desc":"Allows you to enter formatted/syntax-highlighted SQL code","tag":"sql","useoption":"0","example":"[sql]SELECT p.*, t.* FROM posts p LEFT JOIN topics t ON t.tid=p.topic_id WHERE t.tid=7[/sql]","switch_option":"0","menu_option_text":"","menu_content_text":"SQL Commands","single_tag":"0","optional_option":"0","image":""},"tab":{"id":"48","title":"tab","desc":"adds a tab (twelve spaces)","tag":"tab","useoption":"0","example":"[tab]","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"1","optional_option":"0","image":""},"tex":{"id":"41","title":"tex","desc":"LaTeX","tag":"tex","useoption":"0","example":"","switch_option":"0","menu_option_text":"","menu_content_text":"","single_tag":"0","optional_option":"0","image":""},"topic":{"id":"5","title":"Topic Link","desc":"This tag provides an easy way to link to a topic","tag":"topic","useoption":"1","example":"[topic=1]Click me![/topic]","switch_option":"0","menu_option_text":"Enter the topic ID","menu_content_text":"Enter the title for this link","single_tag":"0","optional_option":"0","image":""},"twitter":{"id":"36","title":"Twitter","desc":"A tag to link to a user's twitter account","tag":"twitter","useoption":"0","example":"[twitter]userName[/twitter]","switch_option":"0","menu_option_text":"","menu_content_text":"Twitter Username","single_tag":"0","optional_option":"0","image":"twitter.png"},"xml":{"id":"17","title":"XML Code","desc":"Allows you to enter formatted/syntax-highlighted XML code","tag":"xml","useoption":"0","example":"[xml]<outer>\n <inner>\n <tag param='1'>Test</tag>\n </inner>\n</outer>[/xml]","switch_option":"0","menu_option_text":"","menu_content_text":"XML Code","single_tag":"0","optional_option":"0","image":""}}; CKEDITOR.config.IPS_BBCODE_IMG_URL = "http://example.com/public/style_extra/bbcode_icons"; CKEDITOR.config.IPS_BBCODE_BUTTONS = []; /* Has to go before config load */ var IPS_smiley_path = "http://example.com/public/style_emoticons/default/"; var IPS_smiles = {"total":20,"count":20,"emoticons":[{"src":"mellow.png","text":":mellow:"},{"src":"dry.png","text":"<_<"},{"src":"smile.png","text":":)"},{"src":"wub.png","text":":wub:"},{"src":"angry.png","text":":angry:"},{"src":"sad.png","text":":("},{"src":"unsure.png","text":":unsure:"},{"src":"wacko.png","text":":wacko:"},{"src":"blink.png","text":":blink:"},{"src":"sleep.png","text":"-_-"},{"src":"rolleyes.gif","text":":rolleyes:"},{"src":"huh.png","text":":huh:"},{"src":"happy.png","text":"^_^"},{"src":"ohmy.png","text":":o"},{"src":"wink.png","text":";)"},{"src":"tongue.png","text":":P"},{"src":"biggrin.png","text":":D"},{"src":"laugh.png","text":":lol:"},{"src":"cool.png","text":"B)"},{"src":"ph34r.png","text":":ph34r:"}]}; var IPS_remove_plugins = []; var IPS_hide_contextMenu = 0; var IPS_rclick_contextMenu = 0; /* Has to go after */ /* Load our configuration */ CKEDITOR.config.customConfig = 'http://example.com/public/js/3rd_party/ckeditor/ips_config.js'; </script> <input type='hidden' name='isRte' id='isRte_editor_4fe2476d708e8' value='1' /> <textarea id="ipb_editor" name="Post" class='ipsEditor_textarea input_text'></textarea> <p class='desc ipsPad' style='display: none' id='editor_html_message_editor_4fe2476d708e8'></p> <script type="text/javascript"> ipb.textEditor.initialize('editor_4fe2476d708e8', { type: 'full', height: 200, minimize: 0, bypassCKEditor: 0, delayInit: 0, isHtml: 0, isRte: 1, isTypingCallBack: '', ips_AutoSaveKey: '', ips_AutoSaveData: [] } ); </script> </div> I've tried escaping quotes using several different JavaScript and PHP methods, but no matter what I try I can't get it echoed out without either breaking the page or the editor not working. Does anyone know of a way to get this code stored in a string in a manner that can be then echoed out onto the page as working JavaScript?
Try: <?php ob_start(); ?> <div id="reply-box" style="display: block; width:100%;float:right;"> <script type="text/javascript" src="http://example.com/public/js/3rd_party/ckeditor/ckeditor.js"></script> <script type="text/javascript"> .... your HTML/Javascript </script> </div> <?php $string = ob_get_contents(); ob_end_clean(); ?> I don't have your javascript libs but it appears to show up fine when I echo out $string. PHP is basically copying all of the display content to a buffer and instead of rendering the page, we copy it to a variable.
$variable = <<<END xxx xxx xxx END; echo $variable; Make sure you have END; on it's own line WITHOUT whitespace before it. Hope have helped!
How can I check the source of all image tags in user input using jQuery
I have a form for user input in which users can add images hosted elsewhere using a form. The images are displayed as a small icon which is both a link and which will load an image into a div with stacking order +1 on hover. The image source address is stored in the link tag only. I am using a <div /> with contenteditable=true for the user input. The icon is appended when the form is used. The code for this part works fine. What I would like to do is check the source of all image tags to make sure that users are not adding their own html to display full size images in their post. I am using php on the backend to remove all tags except links and images, but would like to use jQuery to check the src of the image tags before posting. <img src="my_icon" /> //this is what my form will input <img src="anything_else"> //this is what I want to prevent Update: I apologize if this is not clear. Essentially, I don't want the user to be able to input any html of their own. If they want to add an image, they have to use my built in form which inserts something like above.
You could loop over the images and then check the src attribute. $("img").each(function(index) { if ($(this).attr("src") == ...) { // do something } } See http://api.jquery.com/each/ and http://api.jquery.com/attr/ for more information.
Say we have the <div id="editor" /> the jQuery script would look something like this: var srcs = []; jQuery ('div#editor img').each (function () { srcs.push (jQuery (this).attr ('src')); }); srcs will now hold all the src-attributes from the <img />-tags provided in the <div id="editor" /> tag.
Especially for your site following code alerts the links for all images: $('.postimage').each(function(){ alert($(this).attr('href')); });
I have an answer. When users input a < or > in a contenteditable="true" div, the browser replaces them with the html notation < and >. The good news is the images would have never displayed when outputting the user comment. The bad news is that the jQuery based solutions given above will not work to remove the ugly coding. I ended up using php to do it with $post = $_POST['comment']; $imgcheck = true; $stringstart = 0; while($imgcheck == 'true'){ if($stringstart = strpos($post,'<img',$stringstart)){ if ($stringend = strpos($post,'>',$stringstart)){ $strlength = $stringend - $stringstart +4; $substring = substr($post,$stringstart,$strlength); if (!preg_match('~src="\/images\/ImageLink.jpg"~',$substring)){ $post = str_replace($substring, "", $post); } else{ $stringstart = $stringend; } } else{ $imgcheck = 'false'; } } else{ $imgcheck = 'false'; } }
how to return to anchor after post
I have an application that creates quotations, orders etc. and as the user adds items the page reloads and can quite long. The problem is then the user has to scroll down to the last item to add another one - this gets to be quite time-consuming. Is there a way I can get it to do this automatically? I have tried putting anchors on each line item like this; echo "<form action='display_quotation.php' method='post'>\n"; echo "<input type='hidden' name='quote_id' value='$quote_id'>\n"; echo "<input type='hidden' name='item' value='$detail_number'>\n"; echo "<a name='item_$detail_number'></a>\n"; and put the javascript ; echo " <html> <head> <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'> <style type='text/css'> table {font: 13px arial} </style> <script type='text/javascript'> function goToAnchor() { window.location.hash='item_$item'; } </script> </head> <body onload='goToAnchor();'>\n"; This doesn't seem to work - I get in the URL http://my_domain/display_quotation.php?#item_3 but the page always goes to item 2 no matter what item is passed via post.
Change the line window.location.hash='item_$item'; to window.location.hash='item_<?php echo $item; ?>';
Another simple idea that I have is, instead of page-loading and doing scripting to go to the hash, you can choose to do like this: <?php header("location : yourpagename.php#$item"); ?> Another solution is using jQuery, to scroll down to the bottom of the page. A nice example is here using jQuery: http://djpate.com/2009/10/07/animated-scroll-to-anchorid-function-with-jquery/
The problem could be that the browser scrolls to the right anchor, but then the location of the anchor in the page shifts due to a reflow due to styles/images etc. kicking in a bit later. Try going to the same anchor again, after a bit of delay. Do this in your load event handler: setTimeout(function () { with (document.location) hash && (hash = hash); }, 1); Play around with a larger delay if 1ms doesn't cut it.
heres the very simple solution <?php if($POST) { $iItemId = $POST['item_id']; //after saving the item to cart redirect to redirect('domain.com/#'.$iItemId); } ?> <a id="1">Product 1</a> <a id="2">Product 2</a> <a id="3">Product 3</a>