JavaScript - Should This Be A Class - See My Function Obj (i Use Prototype/jquery)
Hey All - I asked this a few days ago.. what I came up with works just fine, but I feel it doesn't take advantage of "classes". If you think I could make this better by turning it into a class or using some other notation, that would be great.
Keep in mind, ALL this does is rewrite a pagination.... for a search return in a lightbox. I have this function called in the return function... Code: var srcpagParams = $H(); function buildPagi(param, currdsplyNum){ var temDsply = new Template('<strong>[#{total_display}<span id="count">#{prevImg} #{links} #{nextImg}</span>'), crnt_link = srcpagParams.set('crnt_link', param), // the page we want to see dsplyNum = srcpagParams.get('paginateNum'), // what is the number of returns per page ttl_lnks = Math.ceil( srcpagParams.get('numFound') / srcpagParams.get('paginateNum')), // total pages data_template = new Hash(); data_template.set('total_display',srcpagParams.get('numFound')); bldImg = function() { var prvB = '<a href="#content" id="pagiPrev" onclick="firesrc(this)">Prev<img src="blank.gif" /></a>'; var nxtB = '<a href="#content" id="pagiNext" onclick="firesrc(this)">Next<img src="blank.gif" /></a>'; data_template.set('prvImg',(crnt_link > 1) ? prvB : ""); data_template.set('nxtImg',(crnt_link < ttl_lnks) ? nxtB : ""); } bldLk = function(){ var holder = ""; if(ttl_lnks > 1){ var linkStr = new Template(' <a href="#content" onclick="firesrc(#{pos});"> Go to page #{pos}</a> '); $R(1,ttl_lnks).each(function(n) { var posit = {pos : n} holder += (crnt_link == n) ? " " + n + " " : linkStr.evaluate(posit); }); data_template.set('links',linkholder); } } bldRng = function(){ var currPaneRg = (dsplyNum * crnt_link) - (dsplyNum - currdsplyNum); data_template.set('range',((crnt_link - 1) * (dsplyNum) + 1 ) + " - " + currPaneRg); $('pages').update(temDsply.evaluate(data_template)).show(); } firesrc = function(cl){ var pagiPane = (typeof cl === "number") ? cl : (cl.id == "pagiNext") ? crnt_link + 1 : crnt_link - 1; var start = crnt_link * srcpagParams.get('paginateNum'); Alertsrc( $F('query') ,(pagiPane)) // pass the query to the json to return the current search request } bldImg(); buildLnk(); bldRng(); }; Since some of the data declared at the top changes depending on the return, I didn't know if I could "initialize" it in a class. But could I turn this into a class and if so - what I just use: var buildPagi = create.Class({ initialize: object.extend({ }) }) Call the function when we are passed some data: Code: buildPagi(somevalue, somevalue2) ** NOTE: I use the libraries prototype and jquery.. so use Create.Class and new Template are within the libraries... etc.. so, is there a more eloquent, or robust way to write what I did above? Similar TutorialsHi, all~..According to ECMAScript, the root of the prototype chain is Object.Prototype. Each object has an internal property [[Prototype]] that could be another object or NULL.... However, it also says that every function has the Function prototype object: Function.Prototype, it confused me, because a function is an object, for a function object, what is its function prototype and object prototype..For example: Code: var x = function (n) {return n+1;}; what is the relationships of x, Object.Prototype and Function.Prototype Thx a lot !!!!!!!!! Hello all I have been trying in vain for many days to resolve a conflict between javascript libraries. I have read far and wide and still have failed to fix this problem, most likely because my programming skills are just about copy and pasting. My homepage uses jquery horizontal css menubar + a combined mootool and prototype accordian type sliding information box in the middle of the webpage. I find that the highlighter of the css menubar does not work when prototype.js is also loaded on the same page. I have read somewhere that $ should be replaced however I have tried every possible option and none works. I have jquery loading first as it is on my template, with this <script type='text/javascript' src='../Web/Templates/jquery-1.3.2.js'></script> <script type='text/javascript' src='js/example.js'></script> And my mootool and prototype loades further below like this <script type="text/javascript" src="scripts/intro/prototype.lite.js"></script> <script type="text/javascript" src="scripts/intro/moo.fx.js"></script> <script type="text/javascript" src="scripts/intro/moo.fx.pack.js"></script> <script type="text/javascript"> function init(){ var stretchers = document.getElementsByClassName('box'); var toggles = document.getElementsByClassName('tab'); var myAccordion = new fx.Accordion( toggles, stretchers, {opacity: false, height: true, duration: 600} ); //hash functions var found = false; toggles.each(function(h3, i){ var div = Element.find(h3, 'nextSibling'); if (window.location.href.indexOf(h3.title) > 0) { myAccordion.showThisHideOpen(div); found = true; } }); if (!found) myAccordion.showThisHideOpen(stretchers[0]); } </script> Could someone please offer me further assistance and enlighten me what other information you require to assist me further. I have attached the example.js inside example.zip file if someone could kindly edit it for myself. Looking forward to your assistance. Sincerely, Lex Array.prototype.each = function (fn) { this.map(fn) } This is my each function that works great in every other browser but IE. UGH! What am I doing wrong? the error points to the this in the function. Is it that IE doesn't like map? Has anyone seen this before? I thought my code was correct. Works perfect in FF, chrome and opera. the canvas text doesn't work in opera, but it does render the features so the each function is working. I'll post the code if needed, but it's huge. here's the script running. http://www.pdxbusiness.com/canvas/golf/ I'm trying to get a div that is contained within another div to show using jQuery. Basically something like Code: jQuery(document).ready(function(){ $('.outerdiv .innerdiv').show(); }); The only problem is that the first div class isn't always the same, it depends on the URL. I have already set it up so that a var is defined based on the URL, but what I am having trouble with is using that in the show() command. So let's say my var is called "name". I would want to be able to write something sorta like $('.[name] .innerdiv').show(); so that, if the value of the var is (for instance) "jack", it would be as if I wrote $('.jack .innerdiv').show(); but I can't figure out how to properly reference the var within those quote marks. Any help? I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. Hi all Just curious how I might be able to target an anchor class with jQuery. For example, If my anchor class is: #nav a.activeSlide { } How can I target it for a fadeTo() ? Not sure of the syntax. Tried variations of: $('#nav a.activeSlide').fadeTo(1000,.5); To no avail. Thanks for your help. Hi! I'm trying to toggle a class and one works and the other does not and I don't know why. I'm just getting my feet wet with jquery and javascript and I figured this was a pretty easy task to take on! Maybe. Link to the page: Franklin Township Soccer Club - Change Field Status My sad, sorry attempt =| Code: $( "li.open" ).click(function() { $( this ).toggleClass( "closed" ); }); $( "li.closed" ).click(function() { $( this ).toggleClass( "open" ); }); The first function works with open, so I figured I'd just use opposite on closed! Ha! I don't think so! In the end within those function there is an element in a form on that page it's hidden. I'd like to change the value from a 0 to 1 for vice versa. That' will be my next step. If you could give me a little nudge in the right direction I'd appreciate it! But first understanding why one works and the other does not, that is the primary mission! I do appreciate any help given! Dave I am attempting the use EasySlider to create a portfolio. Which you can view here. The EasySlider is embedded within an accordion, under the Portfolio tab. I have the first slider functioning properly, which you see by clicking on the Burts Bees tab. However, when you on to the MillionTrees and other tabs the EasySlider does not work. I know that the other tabs are being affected by the function because when you move the images under Burts Bees to a new image and switch back to Million Trees the beginning image changes. I have a feeling I am somehow using the buttons wrong, but I am not sure because I am very new to using JavaScript and jQuery. Any help would be greatly appreciated, thanks. Hi i have a code like this in my web site to slide a panel from left to right: <script type="text/javascript"> <!-- var sipPos = 0; $(document).ready(function() { $("#panel-tab").click(function(e) { //if(autoTimer) clearTimeout(autoTimer); //autoTimer = null; e.preventDefault(); $("#panel").animate({ left: sipPos }, 1764, 'linear', function() { if(sipPos == 0) { sipPos = -856; } else { sipPos = 0; } }); }); }); --> </script> ---CSS--- #panel { width: 864px; height: 369px; position: absolute; top: 195px; left: -856px;/*-856*/ z-index: 200; background:url('../images/bg_panel.png') no-repeat; padding:20px 0 0 18px; text-align:left; } #panel-tab { width: 21px; height: 371px; position: absolute; top: 9px; left: 856px; background:url(../images/panel-arrw-show.png) no-repeat; text-decoration: none; color: #FFFFFF; text-indent:-999999px; } What i want to do is use the animate function in jquery...like this $("#panel").animate({ left: 0 }) but not sure how to use that and on page load make the panel opens and stays open.. Any help Sam not sure if I"m doing this correctly so seeing who can see or tell me if I'm doing this wrong. Say you chose an option from select box it would go into the events table and see that there's not been another event with that id so it'll return 1 and put it inside the text field called Label and when the user fills out the rest of the form it'll put 1 for the label field in the database table when the form is submitted then say the next week rolls around and the user clicks on that same option again and it goes to the events table and sees that there's an occurance of that show via the matching eventids and grabs all the labels with that matching eventid which at this point is only 1 so it would add 1 to that number and return 2 to the Label form text field. form page Code: $('#eventid').change(function() { var eventid = $("select#eventid").val(); var dataString = 'eventid='+ eventid; $.ajax({ type: "POST", url: "processes/booking.php", data: eventid, success: function(data) { $('#label').append(data); } }); }); <div class="field required"> <label for="eventid">Select Event</label> <select class="dropdown" name="eventid" id="eventid" title="Select Event"> <option value="0">- Select -</option> <option value="0">** Recurring Events **</option> <?php $query = 'SELECT id, eventname FROM eventnames WHERE eventtype = "Recurring"'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['eventname']."</option>\r"; } ?> <option value="0">** Singular Events **</option> <?php $query = 'SELECT id, eventname FROM eventnames WHERE eventtype = "Singular"'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['eventname']."</option>\r"; } ?> <option value="0">** Pay Per View Events **</option> <?php $query = 'SELECT id, eventname FROM eventnames WHERE eventtype = "Pay Per View"'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['eventname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="label">Event Label</label> <input type="text" class="text" name="label" id="label" title="Label" readonly="readonly" /> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> processes/booking.php PHP Code: $eventid = (int)$_GET['eventid']; $result = mysqli_query("SELECT * FROM `events` WHERE `event_id` = '$eventid'"); $list = mysqli_num_rows($result); $label = $list + 1; Hi everyone I need some help creating a function which does the same thing for the chosen elements. I have #design1 #design1servicetext and #design1servicebutton. Code: //Service hover// $('#design1').mouseenter(function (){ $('#design1servicetext').css('background-position', '0 -91px') $('#design1servicebutton').css('background-position', '0 -33px') }) .mouseleave(function (){ $('#design1servicetext').css('background-position', '0 0px') $('#design1servicebutton').css('background-position', '0 0px')}); //Service hover end// How can I create a function, in which I have to choose 3 divs to do the animation? A function like Code: animatebg('#design1','#design1servicetext','#design1servicebutton'); Can someone please help me? I've tried so many function tutorials but none of them worked for what I wanted to do. Thank you a lot in advance! So, basically what i'm doing here is hovering over the h2 heading and toggling the paragraph text. What i'm having a problem doing is changing the h3 headings so that they toggle the same way...is there a way to do this within this function without ids/classes? Code: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#hdg').hover(function() { $('div[title=latin]').toggle(); $('div[title=english]').toggle(); $('#').html('<h3>English</h3>'); }); }); </script> I have a slideshow that allows the user to see the previous slide title and the next slide title along with the current slide and its content. I tested locally not in WP and the code worked fine. Once I placed my source within WP everything went south. I inspector the first line in the script seems to be what is having the issues - $(window).load(function(){ and I am unsure what to do next. The source was used from Edit fiddle - JSFiddle the page I am trying to get to work is located here - Sevices | Q&D CONSTRUCTION, INC.Q&D CONSTRUCTION, INC. I am open to any suggestions. Code: <script type='text/javascript' src="//cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/20130801/jquery.cycle2.min.js"></script> <style type='text/css'> .cycle-slide { width: 100%; text-align: center; } img { max-width: 300px; } #next { float: right; } #prev { float: left; } .center { text-align: center; } </style> <script type="text/javascript">//<![CDATA[ $(window).load(function(){ var slideshow = $('.cycle-slideshow'); maxSlides = slideshow.data('cycle.opts').slideCount; slideshow.on({ 'cycle-update-view': function(event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) { UpdateTitles(); } }); function UpdateTitles(){ var currentSlide = slideshow.data('cycle.opts').currSlide; activeSlide = $(".cycle-slide-active"); activeTitle = activeSlide.data('title'); if(currentSlide == 0){ nextTitle = activeSlide.next().data('title'); prevTitle = $(".cycle-slide").eq(maxSlides).data('title'); } else if(currentSlide == maxSlides-1){ prevTitle = activeSlide.prev().data('title'); nextTitle = $(".cycle-slide").eq(0).data('title'); } else { nextTitle = activeSlide.next().data('title'); prevTitle = activeSlide.prev().data('title'); } $('h1').html(activeTitle); $('#prev').html("Previous: "+prevTitle); $('#next').html("Next: "+nextTitle); } UpdateTitles(); });//]]> </script> Hi, I've been playing around trying to recreate the way in which jQuery chains it's functions for it's "select" then "do" behaviour. Note: I don't want to chain functions with jQuery, I want to chain them like jQuery. So based on the jQuery code what I have so far is (doesn't work in IE): Code: var x = function(string) { return new x.fn.init(string); }; x.fn = x.prototype = { message: '', init: function(string) { x.fn.message = string; }, log: function() { console.log(x.fn.message); } }; x.fn.init.prototype = x.fn; var start = function() { x('hello world').log(); }; document.addEventListener('DOMContentLoaded', start, false); The code works but when I watch '$' in jQuery "fn" & "prototype" show up as being "jQuery()" but in my code when I watch "x": "fn" and "prototype" are both shown as objects containing "message", "init" and "log" and in both cases "init" contains "prototype" which contains my three functions again and the nesting continues seemingly infinitely... I'm clearly missing something here. What are they doing in differently in jQuery to prevent this endless nesting loop? I have some javascript code that hides and unhides a menu when a link is clicked, and that is working just fine. What I also need the function to do is switch the CSS class of change_this in the code below to change_that when the link is clicked, and then switch it back to change_this when the link is clicked again. Can someone assist me? I have tried integrating/modifying other scripts I found with this one, but nothing has worked for me. It seems so simple, but I just cant get this thing working. Thanks to anyone who replies with help! Code: <script type="text/javascript"> function HideandUNhideObj(ThisObj){ nav=document.getElementById(ThisObj).style if(nav.display=="none"){ nav.display='block'; }else{ nav.display='none'; } } </script> Code: <li class="change_this"><a id="nav" href="javascript: void();" onclick="HideandUNhideObj('display');"></a> <ul id="display" style="display: none;"> <div id="container_div">stuff</div> I have a question: look at the following html code: /****html***/ <div class='class1'>text1</div> <div class='class1'>text2</div> <div class='class1'>text3</div> ...... /**html***/ If I want to change the background color of the textn by clicking it, what should I do instead of inserting "onclick='someFunction()'" in every div? First of all, I must say that I am recently introduced to JavaScript and I am not fully aware of its complete functionality. So I have an HTML document which has defined within a its body a JavaScript function and I have also a JApplet class which is also loaded in the HTML and can call the JavaScript function. But I have also another Java class which is not an applet and I would like to find a way for this class to be able to call the JavaScript function (but it is essential for this class not to be an applet). I am aware that this would raise some security concerns but it is for local usage and I am interested to hear some ways if possible for this to be done. Thank You beforehand to all of you! Ok...so here is what I have: Code: function myClass() { this.checkLogin = function(name,pwd) { if(name.length > 0 && pwd.length > 0) { $.ajax({async: false, type: "post", url: "url", dataType: "json", data: "data", success: this.parseData}); } } this.parseData = function(data) { this.status = data.status; alert(this.status); } this.getStatus = function() { alert(this.status); } } Everything works above. The first alert shows that this.status was set to 'error'. However, if I call myClass.getStatus(), I get undefined. How can I get the parseData function to set the variables in the parent function? Thanks! Anyone wanna give me some pointers on how prototypes work exactly? ;o Especially in the context of this code: Code: var chatscroll = new Object(); chatscroll.Pane = function(scrollContainerId){ this.bottomThreshold = 20; this.scrollContainerId = scrollContainerId; this._lastScrollPosition = 100000000; } chatscroll.Pane.prototype.activeScroll = function(){ var _ref = this; var scrollDiv = document.getElementById(this.scrollContainerId); var currentHeight = 0; var _getElementHeight = function(){ var intHt = 0; if(scrollDiv.style.pixelHeight)intHt = scrollDiv.style.pixelHeight; else intHt = scrollDiv.offsetHeight; return parseInt(intHt); } var _hasUserScrolled = function(){ if(_ref._lastScrollPosition == scrollDiv.scrollTop || _ref._lastScrollPosition == null){ return false; } return true; } var _scrollIfInZone = function(){ if( !_hasUserScrolled || (currentHeight - scrollDiv.scrollTop - _getElementHeight() <= _ref.bottomThreshold)){ scrollDiv.scrollTop = currentHeight; _ref._isUserActive = false; } } if (scrollDiv.scrollHeight > 0)currentHeight = scrollDiv.scrollHeight; else if(scrollDiv.offsetHeight > 0)currentHeight = scrollDiv.offsetHeight; _scrollIfInZone(); _ref = null; scrollDiv = null; } It's code to make the scrollbars autoscroll down. Full article and extra info he http://radio.javaranch.com/pascarell...837038219.html I sort of understand it but I'm not clear on what prototypes are. |