JavaScript - Centering A Div With Js/jquery
I'm trying to write a function to center a div within a parent div, and I'm having a little trouble. Horizontally, it works fine. Vertically, not so much. This is my function:
Code: function centerObject(idName, idParent) { var parentLeft = $(idParent).position().left; var parentWidth = $(idParent).width(); var parentWCenter = parentWidth / 2; var parentTop = $(idParent).position().top; var parentHeight = $(idParent).height(); var parentHCenter = parentHeight / 2; var objWidth = $(idName).width(); var objWCenter = parentLeft + parentWCenter - (objWidth / 2); var objHeight = $(idName).height(); var objHCenter = Math.abs(parentTop + parentHCenter - (objHeight / 2) - 20); $(idName).css({left:objWCenter,top:objHCenter}); }; The line with the Math.abs call is necessary because without it, the given div ends up halfway off the page up at the top. At least this way it appears somewhere within the browser. The divs in question are all set to position: absolute, but I've tried setting them to all the other possibilities without luck. Or maybe I missed something. This happens in any browser... IE, FF, Chrome, Safari, etc. In any case, anybody have any ideas on where I went wrong? Thanks! Rob Similar TutorialsSo, i have this code which retrieves php files for me using jquery and id love to get it working with Jquery history plugin. I tried modifying the code i got from the ajax demo to work for me, but i just couldnt do it as i do not know any javascript really.. ( actually what i tried was simply to change "#ajax-links a" to "#menu li a" and .html to .php ..but nothing.. :rolleyes: Id be very gratefull if someone would help me out with this one. All related code can be found bellow (the ones that should be needed anyways): This is the code that retrieves php files inside "#content" when item from "#menu li a" with the specified id is clicked Code: $(document).ready(function(){ //References var change = $("#menu li a"); var loading = $("#loading"); var content = $("#content"); //Manage click events change.click(function(){ //show the loading bar showLoading(); //load selected section if(this.id == "home") { change.load(this.className='current-page'); content.slideUp(); content.load("pages/index.php", hideLoading); content.slideDown(); } else if(this.id == "secondpage") { change.load(this.className='current-page'); content.slideUp(); content.load("pages/secondpage.php", hideLoading); content.slideDown(); } else { //hide loading bar if there is no selected section hideLoading(); } }); //show loading bar function showLoading(){ loading .css({visibility:"visible"}) .css({opacity:"1"}) .css({display:"block"}) ; } //hide loading bar function hideLoading(){ loading.fadeTo(1000, 0); }; }); Heres the structure of the menu/content Code: <ul id="menu"> <li><a id="home" class="normal" href="#Home"></a></li> <li><a id="secondpage" class="normal" href="#Secondpage"></a></li> </ul> <div id="content"> <ul id="sec-menu"> <li><a id="link1" class="normal" href="#">Link1</a></li> <li><a id="link2" class="normal" href="#">Link2</a></li> </ul> </div> Heres the code that jquery history plugin uses in demo for ajax Code: jQuery(document).ready(function($) { function load(num) { $('#content').load(num +".html"); } $.history.init(function(url) { load(url == "" ? "1" : url); }); $('#ajax-links a').live('click', function(e) { var url = $(this).attr('href'); url = url.replace(/^.*#/, ''); $.history.load(url); return false; }); }); hi, i have a jquery problem... this script is not working with jquery-1.4.2.min, but it works with jquery-1.2.6.min.js, can anyone help me???the script is the above: (it is not working the tab actions, the slideout works...) http://www.benjaminsterling.com/wp-c...es/sidetab.htm the javascript code is the above: PHP Code: var jqsideTabs; var tabs, h = 50, r = 0,ra = 0; $(document) .ready(function(){ jqsideTabs = $('#sideTabs').addClass('closed'); tabs = jqsideTabs .find('.tab h3') .clone() .appendTo(jqsideTabs) .each(function(i){ var that = $(this), cls = '',ow,newThis, newEl; if( i == 0 ) cls = ' active'; newEl = $('<a href="#" class="tabLinks'+cls+'">' + that.text() + '</a>'); that.replaceWith(newEl); ow = newEl.outerWidth(); if( i == 0 ) ra = ow; else r = ow; h = newEl.css({'top':h , 'right': -ow }).height() + h; newThis = newEl.get(0); newThis.jq = newEl; newThis.i = i; newEl.click(function(){ var el = this.jq; if( jqsideTabs.hasClass( 'closed' ) ){ jqsideTabs.removeClass('closed'); } else if( !jqsideTabs.hasClass( 'closed' ) && el.hasClass('active') ){ jqsideTabs.addClass('closed'); } el .siblings() .removeClass('active') .css({'right': -r }) .end() .addClass('active') .css({'right': -ra }); tabs.eq( this.i ).show().siblings('.tab').hide(); return false; }); }) .end() .parent() .eq(0) .addClass('active') .end() .filter(':not(:eq(0))') .hide() .end(); jqsideTabs.bind("mouseleave",function(){ jqsideTabs .animate({left:-310}, 'fast', function(){ jqsideTabs.addClass('closed').removeAttr('style'); }); }); }); and the html file is: [HTML] <div id="sideTabs"> <div class="tab"> <h3>Tab 1</h3> <div class="gut"> <p>Some text</p> </div> </div> <div class="tab"> <h3>Tab 2</h3> <div class="gut"> <ul> <li>link</li> </ul> </div> </div> <div class="tab"> <h3>Tab 3</h3> <div class="gut"> <ul> <li>link</li> </ul> </div> </div> </div> [/HTML] the problem is that the tab button works, but the content doesnt change...in all of tabs showing the same text(showing all tbas content).... can anyone help...please..... i keep getting the error GET http://code.jquery.com/jquery.min.map net::ERR_TOO_MANY_REDIRECTS & Failed to load resource: net::ERR_TOO_MANY_REDIRECTS when i load my page...and the havascript doesn't work properly on ym page...how do i resolve this. thanx in advance var s="attr" var i=$(s) // jQuery(elem).attr(attr,eval("elm"+attr)); jQuery(elem).$(s)(attr,eval("elm"+attr));//i tried this. how to assign a variable name in the above code(in place of s) so that i need to add an attribute to the element "elem". Ok, I would post my entire data here but then yall would be reading insane amounts of script. I've got a div content jquery slider on my site I am making and it works beautifully in all browsers(took me a while). Then, I decided why not have it where when people click on a "read more" link that it pops up a box, instead of directing to the new page, and displays the contents of a div. It would not work at all. My question is there a possible way to do this?
This has probably been asked times before, but i've tried a few things and im struggling a little. i just wanna center this slideshow which i got to code from http://www.javascriptkit.com Im was just getting the hang of CSS after a little knowledge of using HTML back in the myspace days, but now Javascript is making it a bit more challenging. I tried doing the < center > < / center > thing around it, which did move it but still kept a scroll bar at the bottom and was mroe right aligned if anything. Its from big cartel. The code for the page is below and the link to the page is www.therobinsbobbin.com/welcome-page Code: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{{ store.name }} — {{ page.name }}</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en-us" /> <meta name="description" content="{{ page.meta_description }}" /> <meta name="keywords" content="{{ page.meta_keywords }}" /> <link href="/products.rss" rel="alternate" title="Product RSS Feed" type="application/rss+xml" /> <link href="{{ theme | theme_css_url }}" media="screen" rel="Stylesheet" type="text/css" /> <script src="{{ 'prototype' | theme_js_url }}" type="text/javascript"></script> <script src="{{ 'store' | theme_js_url }}" type="text/javascript"></script> <div id='mydiv'> <script type="text/javascript"> // Flexible Image Slideshow- By JavaScriptKit.com (http://www.javascriptkit.com) // For this and over 300+ free scripts, visit JavaScript Kit- http://www.javascriptkit.com/ // This notice must stay intact for use var ultimateshow=new Array() //ultimateshow[x]=["path to image", "OPTIONAL link for image", "OPTIONAL link target"] ultimateshow[0]=['http://img715.imageshack.us/img715/120/newslide1.png', 'http://www.therobinsbobbin.com/home'] ultimateshow[1]=['http://img214.imageshack.us/img214/3893/newslide2.png', 'http://www.therobinsbobbin.com/home'] ultimateshow[2]=['http://img268.imageshack.us/img268/9044/newslide3.png', 'http://www.therobinsbobbin.com/home'] //configure the below 3 variables to set the dimension/background color of the slideshow var slidewidth="300px" //set to width of LARGEST image in your slideshow var slideheight="261px" //set to height of LARGEST iamge in your slideshow var slidecycles="continous" //number of cycles before slideshow stops (ie: "2" or "continous") var randomorder="no" //randomize the order in which images are displayed? "yes" or "no" var preloadimages="yes" //preload images? "yes" or "no" var slidebgcolor='white' //configure the below variable to determine the delay between image rotations (in miliseconds) var slidedelay=1500 ////Do not edit pass this line//////////////// var ie=document.all var dom=document.getElementById var curcycle=0 if (preloadimages=="yes"){ for (i=0;i<ultimateshow.length;i++){ var cacheimage=new Image() cacheimage.src=ultimateshow[i][0] } } var currentslide=0 function randomize(targetarray){ ultimateshowCopy=new Array() var the_one var z=0 while (z<targetarray.length){ the_one=Math.floor(Math.random()*targetarray.length) if (targetarray[the_one]!="_selected!"){ ultimateshowCopy[z]=targetarray[the_one] targetarray[the_one]="_selected!" z++ } } } if (randomorder=="yes") randomize(ultimateshow) else ultimateshowCopy=ultimateshow function rotateimages(){ curcycle=(currentslide==0)? curcycle+1 : curcycle ultcontainer='<center>' if (ultimateshowCopy[currentslide][1]!="") ultcontainer+='<a href="'+ultimateshowCopy[currentslide][1]+'" target="'+ultimateshowCopy[currentslide][2]+'">' ultcontainer+='<img src="'+ultimateshowCopy[currentslide][0]+'" border="0">' if (ultimateshowCopy[currentslide][1]!="") ultcontainer+='</a>' ultcontainer+='</center>' if (ie||dom) crossrotateobj.innerHTML=ultcontainer if (currentslide==ultimateshow.length-1) currentslide=0 else currentslide++ if (curcycle==parseInt(slidecycles) && currentslide==0) return setTimeout("rotateimages()",slidedelay) } if (ie||dom) document.write('<div id="slidedom" style="width:'+slidewidth+';height:'+slideheight+'; background-color:'+slidebgcolor+'"></div>') function start_slider(){ crossrotateobj=dom? document.getElementById("slidedom") : document.all.slidedom rotateimages() } if (ie||dom) window.onload=start_slider </script> </div> {{ head_content }} <html> <body id="{{ page.permalink }}-page" class="{{ page.permalink }} {{ page.category }}"> <div id="wrap"> <noscript> <div class="error" id="error"> <ul> <li>JavaScript must be enabled to use this store!</li> </ul> </div> </noscript> {% if errors != blank %} <div id="error" class="error"> <ul> {% for error in errors %}<li>{{ error }}</li>{% endfor %} </ul> </div> {% endif %} {% if store.website != blank %} <div id="website"> <a href="{{ store.website }}">Back to site</a> </div> {% endif %} <div id="main-content"> {% if page.category == 'custom' %} {{ page_content | paragraphs }} {% else %} {{ page_content }} {% endif %} </div> </div> {% if theme.show_newest %} <div id="newest" class="pod"> <h3 class="newest-title"><span>Newest Products</span></h3> <ul class="newest-list"> {% get 5 products from products.all order:'newest' %} {% for product in products %}<li>{{ product | link_to }}</li>{% endfor %} {% endget %} </ul> </div> {% endif %} {% if theme.show_top_selling %} <div id="top-selling" class="pod"> <h3 class="top-selling-title"><span>Top Selling</span></h3> <ul class="top-selling-list"> {% get 5 products from products.all order:'sales' %} {% for product in products %}<li>{{ product | link_to }}</li>{% endfor %} {% endget %} </ul> </div> {% endif %} {% if theme.show_products_feed %} <div id="feed" class="pod"> <h3 class="feed-title"><span>Feed</span></h3> <ul class="feed-list"> <li class="li-1"><a href="/products.rss" title="Product RSS Feed"><span>Product RSS Feed</span></a></li> </ul> </div> {% endif %} <div id="footer"><span></span></div> </div> <div id="extra-1"><span></span></div> <div id="extra-2"><span></span></div> <div id="extra-3"><span></span></div> <div id="extra-4"><span></span></div> <div id="extra-5"><span></span></div> <div id="extra-6"><span></span></div> </div> </body> </html> I have a problem in centering my popup window. I want it centered in the page when it pops up. The problem is in the code that is red. Here's a part of my script: if (counter == 0) { var myRes = "<html><head>\n"; myRes += "<title>Popup Window</title>\n"; myRes += "</head><body>\n"; myRes += "<div style='text-align:center'>\n"; myRes += "<p>Search character '<b>" + searchChar + "</b>' not found in text string!</p>\n"; myRes += "<input type='button' value='Close Window' onclick='window.close()'>\n"; myRes += "</div>\n"; myRes += "</body>\n</html>"; var popup = window.open("", "Popup", "top=10,left=300,width=300,height=100"); popup.focus(); popup.document.write(myRes); popup.document.close(); I have an issue with my div visibility toggling Code: function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } I call it from an image map he Code: <area shape="rect" coords="234,-12,480,203" href="#peripherala" onclick="toggle_visibility('peripherala');toggle_visibility('shadow');return false"/> and I do the return false to stop the thing from jumping all over the place, but where i click next, the page scrolls down to center on that point, which is really annoying. How do I stop it? Thanks for any help.... Hey, ive been strugglng all day to centre a DIV with javascript in the centre of my page. Ive created a modal popup and id like it to stay in the screen even if the page has been scrolled down. And no matter what i try i cant get it to actually hit the centre of the screen. I should add that im totally new to javascript but decided i cant avoid learning javascript forever so here are my pathetic efforts.. Code: function ShowPopup(hoveritem, thepopup, theimage) { popVar = document.getElementById(thepopup); //document.getElementById('hoverpopup').style.paddingLeft = screen.width/2-250; //document.getElementById("hoverpopup").style.paddingTop = screen.height/2; // Set position of hover-over popup //popVar.style.top = hoveritem.offsetTop + 50; //popVar.style.left = hoveritem.offsetLeft + 100; // Set popup to visible popVar.style.visibility = "Visible"; } Ive tried loads of other things too, whats commented out has been my last effort. Im doing other things too in the function in case you wondered. But any ideas how i can do this, sorry if ive not been too clear! Hi all, Here's the situation. A client has a 1440 wide flash move in .swf format that serves as in intro to the site. They want the flash movie centered on the screen even if the resolution is lower, at 1024 or whatever. At this point my idea is to wrap the flash object in a div and center that div using javascript so that it centers no matter the screen width, but I don't know exactly how to do this....any ideas? thanks very much. Hola! I'll give you a little background before I ask you guys my question! I have a Header, a rectangle of 800x100 and directly below that I have Spry Collabsible panels stacked on top of each other with my menu items 'Home' 'About us' etc. My question is... does anyone know of a way I could vertically center everything on the page, so that when the panels are closed it is nicely in the centre and when you open one, the header moves up to allow room for the content and the whole thing stays vertically centered on the page. I'm guessing this will need some kind of fancy javascript to make possible. Thanks in advance for any advice you can give! Adam Hi guys, I don't know if this is possible at all, but I thought it was worth a shot asking. http://www.applicate.com.au/home I have a slideshow in a div that is 1800px wide, and a smaller content area which is 980px wide. Usually I would use a background image for this, but it needs to be a slideshow. It works great on larger screens, but not on small screens. I've removed the horizontal scrollbar, but when viewing on a small screen, obviously the content isn't in the center. I know centering this isn't possible in CSS, is it possible in JavaScript? Otherwise, I guess I'll look for a module that is a background image slideshow. Thanks in advance for any suggestions (: Hi, I have this js script which is working on mouse click, what is my requirment is that it do the same function wiht on mouse over: click: function(e) { var el = this; el.blur(); // if the image was not preloaded yet then wait if (el.zoomimageCfg.loading === true) { return false; } //zoom it in if not zoomed already if (el.zoomimageCfg.zoomed == false) { EYE.zoomimage.zoomIn(el); //else zoom it out } else { EYE.zoomimage.zoomOut(el, false); } return false; }, Thank you Best Regards, mnightwalker Hi Guys, Please check this link out. I'm curious if you can attain the same functionality with jquery. Which include the hover over effects and sliding. If this can be done can you point me in the right direction to find some documentation to start learning. Thanks. http://www.gensler.com/#projects Hi All, i have an autosuggest feature on my site where the user searches for a product and as they type it lists matching products from my database. here is the javascript/jquery code Code: $(document).ready(function(){$(document).click(function(){$("#ajax_response").fadeOut('slow');});$("#keyword").focus();var offset=$("#keyword").offset();var width=$("#keyword").width()-2;$("#ajax_response").css("left",offset.left);$("#ajax_response").css("width",width);$("#keyword").keyup(function(event){var keyword=$("#keyword").val();;if(keyword.length) {if(event.keyCode!=40&&event.keyCode!=38&&event.keyCode!=13) {$("#loading").css("visibility","visible");$.ajax({type:"POST",url:"/ajax_server.php",data:"data="+keyword,success:function(msg){if(msg!=0) $("#ajax_response").fadeIn("slow").html(msg);else {$("#ajax_response").fadeIn("slow");$("#ajax_response").html('<div style="text-align:left;">No Matches Found</div>');} $("#loading").css("visibility","hidden");}});} else {switch(event.keyCode) {case 40:{found=0;$("li").each(function(){if($(this).attr("class")=="selected") found=1;});if(found==1) {var sel=$("li[class='selected']");sel.next().addClass("selected");sel.removeClass("selected");} else $("li:first").addClass("selected");} break;case 38:{found=0;$("li").each(function(){if($(this).attr("class")=="selected") found=1;});if(found==1) {var sel=$("li[class='selected']");sel.prev().addClass("selected");sel.removeClass("selected");} else $("li:last").addClass("selected");} break;case 13:$("#ajax_response").fadeOut("slow");$("#keyword").val($("li[class='selected'] a").text());searchValue=document.getElementById('keyword').value; searchValue = searchValue.replace( /\([^\)]*\)/g, "" );searchValue = searchValue.replace(/^\s*|\s*$/g,'');searchValue=searchValue.replace(/(\s-)/gi,"");searchValue=searchValue.replace(/\s/gi, "_");searchValue=searchValue.replace(/[:',]/gi,"");window.location="/CDs/"+searchValue.toLowerCase();break;}}} else $("#ajax_response").fadeOut("slow");});$("#ajax_response").mouseover(function(){$(this).find("li a:first-child").mouseover(function(){$(this).addClass("selected");});$(this).find("li a:first-child").mouseout(function(){$(this).removeClass("selected");});$(this).find("li a:first-child").click(function(){$("#keyword").val($(this).text());$("#ajax_response").fadeOut("slow");});});}); this runs this php script to get the product names PHP Code: <?php session_start(); include("config.php"); $keyword = $_POST['data']; $keyword = preg_replace("/s*\(.*\)/i", "", $keyword); $keyword = ucwords($keyword); $sql = "select DISTINCT prodName,prodShortName,prodCategory from ".$db_table." where (".$db_column." like '".$keyword."%' AND prodCategory = '".$_SESSION['subpage']."') limit 0,10"; $result = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($result)) { echo '<ul class="list">'; while($row = mysql_fetch_array($result)) { $category = strtolower($row['prodCategory']); $str = ucwords($row['prodName']); $start = strpos($str,$keyword); $end = similar_text($str,$keyword); $last = substr($str,$end,strlen($str)); $first = substr($str,$start,$end); $link = "/".$category."/".$row['prodShortName']; $final = '<span class="bold">'.$first.'</span>'.$last; echo '<li><a href="'.$link.'">'.$final.'</a></li>'; } echo "</ul>"; } else { echo "0"; } ?> which works fine, what i am trying to acheive is to pull out the category of the products in the list and use it in the script. so where it says this Code: window.location="/CDs/"+searchValue.toLowerCase();break; i want the value of the php value $category to be. but i have no idea how to do this or if it is even possible? any help is appreciated many thanks Luke i am a newbie to jquery and need help. i want to alert anything when i click at any button that have the class .resetBtn using jquery. I know doing it with javascript is much easier but i learning jquery so trying to create function by myself. my code currently does not work when i click on my button. Code: $(".resetBtn").click(function() { alert ("asd"); }); All, I have the following jQuery code: Code: $("#other").click(function(){ var checked = $(this).is(':checked'); if(checked){ $('textarea#other_text').removeAttr("disabled"); }else { $('textarea#other_text').attr("disabled", "disabled"); } }); This works fine. However, what I'm allowing the users to do is edit this field. So I have the following PHP code: PHP Code: <input type="checkbox" name="other" value="x" id="other" <?php if($resultsetedits['other']=="x"){ echo "checked"; } ?>> Other:<br>If you choose other, please explain what other options you'd like us to do to your photo:<textarea name="other_text" rows="3" cols="119" id="other_text" disabled><?php if($resultsetedits['instructions']!=""){ echo $resultsetedits['instructions']; } ?></textarea> Since the checkbox is checked with the PHP code the click function to jQuery never gets invoked and my textarea remains disabled. Is there anyway to basically invoke the jQuery code with my PHP script? Thanks in advance. i want get value form path : ex.. xxx.com/index.php?cat " cat " read cookie with jquery who? |