Jquery has element creation methods built in, on top of document.createfragment, which is universally accepted as the best way to store unrendered HTML. Check out this presentation from john resig. http://ejohn.org/apps/workshop/adv-talk/
EDIT Some folks are having a hard time reading this. Here's a print view of the presentation. https://drive.google.com/file/d/1JTbSbqyygCq8-HDS2ft9VhqFYg1kXmm2qcn-6Z4nzr9Nl3egHQcJklYMB9wCdpp7j45zIcBFPBNLEc7k/edit?usp=sharing
I forked with some minor modifications: http://jsfiddle.net/gUdGk/4/
Quick summary:
$this
for the click()
scope. This saves writing $(this)
frequently, and will save a call to $(...)
every time you are referring to the same object*tab_parent
and current_tab
to $tab_parent
and $current_tab
. This can help identify vars which are jQ objects when reading code.css(...)
calls and chained the .animate(...)
functionIn other scenarios, where you have var current_tab_content_id = $current_tab.attr('href')
followed later by $(current_tab_content_id).whatever
, you may find it more practical to set up a jQ object to refer to rather than referring to $(myVariable)
.
EG: var $current_tab_content = $($current_tab.attr('href'))
It is OK in your Fiddle example because each instance is only used once, but if used more than once it is akin to using $this
as above.*
* In many cases the performance gained by doing $this
is pretty negligible. However, it's useful where performance is important, and it's easier to read, write, and maintain as well.
Edit: As an afterthought (it's probably not that important at all), something you might consider when this kind of thing is used in a website is some "JavaScript is active" styling.
That is, by default your div.tab_content
s might be visible and not absolutely positioned. When your page is ready you might use JavaScript to add a "js" class to the <body>
, and you could in your stylesheet do body.js div.tab_content { display: none; position: absolute; etc...}
.
You've used href
and id
attributes as they should be. This way, if someone without JS comes along they can still use the menu and see all the content.
It is reasonably rare in most cases to find people with JS disabled, but it still happens from time to time.
Hope this made sense!
I know this is /r/jquery but take a step back and learn JavaScript properly. There's no way you'll regret doing this. Here's an amazing list of js learning resources: https://medium.com/javascript-scene/learn-javascript-b631a4af11f2
It would really help things if you were to make a jsFiddle or equivalent.
I've put together this bare-bones example that you can update: It's got all the external resources loaded already for jQuery and UI.
So here would be one way to do it, just expanding on your fiddle: JSfiddle
A couple things I did:
Hope that helps answer some questions, and happy holidays to you too!
Edit: oops forgot to save fiddle, working now
For a start you have the input looking for a :selected value (obviously inputs don't have selected values). Then the values you retrieve are strings so you need to convert them to Integers
Here's the working Fiddle.
Edit: The right link!
"imgWrapper" should be a class, not an id. Only use IDs when it's a unique element.
In your CSS and JS, change every "#imgWrapper" to ".imgWrapper"
In the HTML, change <div id="imgWrapper"> to <div class="imgWrapper">
Updated fiddle: http://jsfiddle.net/5whgt/8/
There is no jQuery-specific platform, as jQuery is nothing but Javascript and requires a js engine as well as something for visuals.
That said, Air is really just a standalone Webkit runtime with some other stuff bolted on. You can use jQuery like normal and HTML like normal. Its like having a chromeless browser to do anything you want to with... just like OS X widgets. Its a little dated, but I built desktop apps for Time Warner Cable for Dashboard, Vista Gadgets, Air and iPhone using 90% of the same codebase between platforms.
Also, there's Titanium, which, despite its huge play in the mobile market, still does desktop apps as well, I believe.
Scrap your code and just use jQuery validation. Not only is it an amazing plugin but it's so popular that it's hosted on microsoft's cdn:
http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Validation_Releases_on_the_CDN_2
Edit: Just so you know how easy it is... All you would need to do is:
Remove your jquery code.
Add the script to your page.
Add the class 'required' to the 3 inputs you have. Also add the class 'email' to the email input.
Then add > $(document).ready( function() { > $('yourForm').validate(); > });
Your last example should have worked.
$_window_settings
→ Object
$_window_settings['my_computer']
→ Array
$_window_settings['my_computer'][0]
→ Object (first and only element of the Array)
$_window_settings['my_computer'][0]['title']
→ property of the Object
It's usually wise to add a variable in such case, i.e.
var myComputerSettings = $_window_settings['my_computer'][0];
and now you have your title in
myComputerSettings.title;
Strictly dealing with the JS, the first thing you may want to get in the habit of is re-using functions for multiple DOM elements. In your case, since the behavior on both #left and #right is the same, you can just use the same function.
You'll also want to use the updated .on() method for events which was introduced in jQuery 1.7. This will also prevent you from ever slipping into the dark hole that is live().
Here's my take, which obviously could be optimized further. http://jsfiddle.net/hwwPc/
use
.css('visibility','hidden')
to show it again
.css('visibility','visible')
Visibility maintains spacing.
EDIT: Here is an example
EDIT #2: 'visible' and not 'visibile'. Thanks bobmitch.
yo.
Quick general hints/notes:
Concerning your problem:
Things I should have maybe done but didn't:
Selector with classes instead of data attributes. I don't like doing traversal with $("[data-id='2']"). I'm pretty sure it's slower than doing something like $(".vote-id-2")
Store the current value in a data-attribute. This is for future, if, let's say, you want to display an image or graphic bar instead of a value.
Cheers.
You can't animate your background-size with non-numeric values such as 'cover', at least not yet.
Here's another approach with the same result : http://jsfiddle.net/k3qw9ka1/2/
Background image is moved into the body:before pseudo-element, and uses transform:scale() for the animation.
[Edit] Added CSS vendor prefixes to the example
First of all, put this on codepen.io and open the console.
var Date = Date()
to var myDate = Date()
var Time = Date.gethours();
should be var Time = myDate.getHours();
-- jAvAsCrIpT is CASE-sensitive.console.log(tijd);
? Guessing a leftover variable? // comment that out
if (time >=17 && Time <23) {
becomes if (Time >=17 && Time <23) {
because JS is case-sensitive.Honestly, just learn to use your console, then just trial-and-error it until it works, lol.
.bg-warning has the background-color set to !important. If you use your own classes and don't set the background-color to !important, it'll work: https://codepen.io/piko_/pen/aGXPXV?editors=1111
You'd want jQuery Waypoints.
Here's a very basic and simple working Waypoint Demo.
Note that this is a jQuery specific solution in that it requires a jQuery plugin.
Why not pure CSS? I put this together in 5 minutes, do note it uses the HTML5 figure and figcaption elements so it may be broken in some really old IE versions:
Edit: ohh, I skip-read the post assuming the title and link were sufficient. Why do you want the boxes to rescale based on browser sizes? From my experience this rarely results in a good user experience. Either way, you could look into vw/vh units but they're pretty unsupported by browsers right now. You can also combine the above solution with a little bit of javascript that changes the default font-size of the body in the onresize event.
Here's an example of that; notice the differences from the previous version to learn how to also fix the font-size for the figcaption: http://jsfiddle.net/W5cRB/1/
> I don't doubt that - yet, I don't know the good way. That's why I was asking.
What I mean is that the good way is simply not having different rules for different browsers. With other words, not use such classes, period.
Some people use Modernizr to apply different styles depending of what features the browser supports. I myself consider that a pretty poor solution in reality, but feature detection is definitely the only "correct" solution if you really need to provide different styles to different browsers.
I've been able to get it working to your first goal. This example just changes the revert option to 'false' when it's been dragged out, then resets it to '100' when it's over.
However it doesn't animate the helper. I think in order to do that you'd need to clone the helper before it's destroyed, then animate the clone how you like after the actual helper gets destroyed. Does that make sense?
Edit: This might also work.
You should see jQuery as a library of commonly-used functions for JavaScript. And being able to have them all at your fingertips just by adding one include line to your HTML is super-convenient and time-saving.
I will also point out, that that "you might not need jquery" is kind of misleading. 1) jQuery is just Javascript. So you never "need" it. You could just re-write the functions from jQuery as you need them. But the point is… isn't your time better spent not re-writing code? 2) Several of those comparisons on that site are not equal. A quick example I made demonstrates a common situation where their "show" code doesn't work, but jQuery does.
Something (sloppy, mind you) like this? I've never worked with browser extensions but if you're just looking for jQuery you are indeed correct that it's doable. I'd be happy to help more if you need.
Best practices? What your suggesting is adds useless code (so does unbind/click in my post, I was just mentioning the dangers). Unless you have a specific reason for doing "off", there is no reason to do it in your statement.
$( [container] ).on('click', [element], [function]);
You don't need anything more than that, that is one of the benefits to using "on".
If the OP decides instead to initialize clicks() each time, then that is where I made him aware regarding the unbind because you will have the same issue. In fact if he used your code without "off" he would run into the same issue and my reply would still be the same that some sort of off/unbound would be needed. Or he could just do "on" and watch the whole container or doc body, as suggested by chmod.
I guess you meant use on/off vs bind/unbind as far as best practices, not the actual code flow suggested.
> ge legit even said you could oet someone else make it if you want since he'll be asking questions about the code to see how much of it i understand.
That's the same trap as "sure, keep the book on your desk during the test", he knows you wont have the time to look up everything and finish the test in time. Students that didn't study will still fail and those that did study will have a quick reference, which they would have in the real world as well.
It's not that hard a task, if you do it yourself and only manage to get it 50% done but you can explain everything you did you'll be fine. Stammering through someone else's code will be a fail.
Here you go: https://codepen.io/anon/pen/QxQxrJ
$50 please.
Is this a typo?
<div id="example"> <p>text</p> <div> <!-- shouldn't this be "</div>"? -->
Did you mean to type </div>
at the end? Otherwise, you will get weird results trying to append that string.
See this codepen for an example - https://codepen.io/anon/pen/vjeYZz?editors=1010
I'm no pro, but this is what I see:
Looking at the source, I can see a duplicate block of code initiating the same slider twice. Appearing around lines 589 and again near 659.
try {
$(window).load(function () { $('#slider').nivoSlider(); });
} catch (e) {}
Not sure if you simply don't have the right selector for the second one or this is some issues with your setup spitting out duplicate code.
$('#slides2').nivoSlider();
Running the above statement in the console initiates the slider just fine, so I'm guessing you're simply never initiating it.
Also, in the future it's very helpful to set up a reduced test case for troubling code with a service like jsfiddle or codepen.
change is fired only once for the rediobutton you actually clicked. The other button, even if its state changes too, doesn't fire the event, so the class does not disappear from the div.
Try this:
$("#flip").hoverIntent(function(){ $("#panel").slideToggle("slow"); }, function(){ $("#panel").slideToggle("slow"); });
Hoverintent requires functions for both over and out. Check out the documentation if you haven't already, there's a few other things you can do with it, and it might help understand what's going on: http://cherne.net/brian/resources/jquery.hoverIntent.html
Edit: Here's a quick fiddle: http://jsfiddle.net/WATcL/
Double edit: This isn't totally optimal, it's just to show what was going wrong. This could definitely be tweaked and improved. E.g. you might want to cache your panel selector in a variable, or use a configuration object as shown on the documentation page linked above.
I like to bind to the window resize event, then just check values to determine whether viewport aspect is landscape or portrait.
Here's a fiddle: http://jsfiddle.net/WPRuR/1/
You may want to throw a debounce in there, or use if statements to check for square ratios for browsers, but that's the general idea.
it's not perfect, but it's late and a start: http://jsfiddle.net/pP7gS/
some thoughts:
-Have the divs animate in order based on which one was clicked using the .next() method
-Use percentages widths instead of static widths on your starting blocks, so your divs can be responsive
-Although I didn't do a very good job at it, try to write only one function that slides the blocks to the left so more blocks can be added at the start without having to write another function. Additionally, less space will be needed for only one .click event vs n.
-(I'll check back on this tomorrow to see if you've made any progress)
You should always put events listener in document ready. This makes sure that the target has loaded in the DOM before attaching anything to it.
I unfortunately can't reproduce your problem.
What you could do is switch the regular bind to .on().
Try it with this:
Could be a couple of things:
You mentioned outerHeight, but did you know you can pass it true like so(this takes the margin into account, setting to false I believe doesn't): $('.thing').outerHeight(true);
It's probably because it's getting the height before the content in the div have finished loading. so you could try document load function instead of a document ready function: https://stackoverflow.com/questions/8396407/jquery-what-are-differences-between-document-ready-and-window-load
Alternatively if they are custom fonts and you don't want to use .load, you might be able to get a callback from the font replacement service or pass that through google's web font loader to use their "loaded" callback function though can't really tell if they are custom fonts.
You could also do this on a setTimeout function on the document ready if you wanted (delaying the call on document ready by 300ms or something) though that's not as reliable.
Edit: Oh and /u/Skyrocker is also correct, the + joins the javascript together with the strings within the single quotes.
Well, to start with... If you're using jQuery... use jQuery ;)
function launch(imgUrl){ var $box = $('<div>') .addClass('opened-image') .append('<img src="http://placehold.it/' + imgUrl + '">'); var $win = $('<div>') .addClass('overlay') .append($box) .on('click.Bst', function(event) { if ($win.is(event.target)) { $win.fadeOut('slow', function() { $win.remove(); }); } }); $('body').append($win); }
Browser detection is bad because browser features change as the browser is improved. You don't want to have to change the code down the road when firefox begins supporting the technology you're using for the site.
The better solution is feature detection libraries like Modernizr. With that you just target the feature you need. When the browser supports it, it'll work, when it doesn't, it won't. And this covers edge case browsers like older Chrome or Opera versions that may not support it as well, or other Gecko based browsers that have similar support to Firefox.
I'm not sure if I understand the question. jQuery Mobile's default behavior is to load external pages via Ajax specifically to enable transitions (see here).
Just don't put the rel="external"
or data-ajax="false"
attributes on your links and you should see transitions between pages--even when they're in external files.
Just started hacking on JQM... I think the answer is yes. JQM has some very specific mark up for the framework work http://jquerymobile.com/demos/1.1.0/docs/about/getting-started.html
Also, I'm not sure how your current webapp works in terms of xhr scripts but JQM "hijax" all pages (xhr to load a page within a block called <div data-role="page"> ... </div>)
Hey,
While serdecochayuyo's answer is great for 2 async scripts, if you have more than 1, you should use Promises.
http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/
gotta pay them tho if it's for a business.
Google i think has a free chart api that has been updated pretty nice recently.
Since your data is in xml you prob will have to parse xml to json obj or some shit (plenty of java/c++/etc libs that do this for you) good luck.
It looks like you were mixing up your labels and values. You were assigning your 'data-value' with the label ("Option 1" vs "option1").
Here's your example fixed up:
You might want to create a minimal example on jsbin.com or jsfiddle.net so people can help you.
Are you using other plugins that aren't listed in your code above? AFAIK there is no built-in jQuery 'highlight' function. Your best bet is to use jQuery to add a CSS class that controls the background-color of your selected tab.
seems like you would need some sort of event to trigger the process of "iterating over each element and adding the value within the inputs" - probably a function containing the $.each that gets triggered upon $.live('click')
something like this, perhaps? http://jsbin.com/hapidugucu/3/edit?html,js,output
it would be helpful if you posted your code on jsbin to understand the exact html structure as well!
This should cover whatever you want to do.
rgIgnore is a regex of classes you want to ignore (not remove);
$(".resetBox a").click( function(){ var newClass = $(this).attr("name"); var allClasses = ""; var rgIgnore = /views-row|ignore/g; $("#ajCall .views-row").each(function(){ $(this).addClass(newClass); allClasses = $(this)[0].className; $(this).removeClass(allClasses.replace(rgIgnore,"a").replace(newClass, "")); }) });
added to JSbin
try $(":button[id$='rptItems_ctl00_btnShowAll']").val("hi");
Assume that rptItems_ctl00_btnShowAll is the static part of the name; if its not just replace this value with whatever static value you want to search for.
You were pretty close; let me give you some additional info:
Instead of "for" you want to specify the tag you are looking for, in this case the button's id (could use name etc). And finally, the $= specifies any field ending with the given string.
EDIT:
Here is a quick working sample for you to reference.
After skimming through it, i have to say that you (and anybody else who is seriously passionate about programming) will enjoy "Clean Code" by Robert C. Martin.
I stumbled upon it in a stackoverflow discussion about books that greatly influenced software developers in their career (see link above).
I'm halfway through it, and it's everything you'd expect, and much more. Read it, really.
Take it to the next level. Plug into other API's like Bacon Ipsum and other ipsums. Then create services for various MV* frameworks so they just call a function and it uses your plugin. I know it's over the top, but this is exactly how I learned how to do a lot of things.
This got me part of the way there. Since I'm using AngularJS, however, including jQuery in the controller is not very good practice so I have to include it in a directive. This means I might need to find a way to somehow listen for a CSS change or something to that effect. Here is a jsfiddle example showing what I mean. I realize this is the jQuery subreddit, so you can just ignore the AngularJS bits if needed. I have your code hooked up to a 'mousemove' event for the time being, so you can see the expected behaviour. Simply keep moving the cursor over the progress-bar, and you should see the bar jump back to 0% once the counter reaches 100. Hopefully this should be sufficient to illustrate what I'm trying to achieve.
Edit: I actually found a much cleaner way of getting the job done using ng-class. Here is the example.
I'm not sure if I follow...Setting it to 0 causes the easing animation to fire, sliding the bar back to 0%. I've made a jsfiddle example to better illustrate what I'm talking about here.
This should give you a general idea of one possible solution:
$(function () { function fetchWeatherData(city) { return $.get('http://api.openweathermap.org/data/2.5/weather?q=' + city); }
function addCityWeather(cityWeatherData) { $('#weather') .append($('<h2>', { text: cityWeatherData.name })) .append($('<p>', { text: cityWeatherData.temp + '\u00B0' })); }
function fetchAndAddCityWeather(city) { fetchWeatherData(city) .then(function (response) {
var cityWeatherData = { name: response.name + ', ' + response.sys.country, temp: response.main.temp };
addCityWeather(cityWeatherData);
}, function () { console.log('Unable to retrieve weather data for %s', city); }); }
fetchAndAddCityWeather('London, UK'); fetchAndAddCityWeather('Paris, France'); fetchAndAddCityWeather('New York, NY'); fetchAndAddCityWeather('Dallas, TX'); });
...and a working JSFiddle
from a high level, add a class to the cell(s) with the number, and a class on the input. add an on() event to the tr, find the child .number, get it's html, find the child input, set it's val to the html you just found.
super duper simple example: http://jsfiddle.net/r5fjo6q4/1/
I'm surprised this has no answers. Take a look at my updated version.
I think you really need to take a step back and learn about what you're working with, especially HTML. For example, you had all that code for switching between different radio buttons, when all you had to do was put them in the same group by giving them the same name. And you had code for checking the first one on page load, when all you needed to do was add a checked
attribute.
Other notes:
*I'm assuming it's cents, but I'm not sure which currency uses both a dollar sign and a decimal comma.
You were missing a "px" after the left attribute and I changed the height animation to a scale transition, but other than that this is absolutely perfect. Thank you so much.
PROTIP: Use jsfiddle.com when pasting your code, it'll allow everyone to debug your code easier/faster.
Original: http://jsfiddle.net/k0to2rfr/
I think the problem is with the ID. IDs are unique, there shouldn't be 2 elements with the same ID. I'd add the class (such as .datepicker) and add that to inputs, the amend your jQuery selector to $(".datepicker").
This is because the keyup is going to trigger on EVERY keyup event. So every time it fires, it grabs the content of the text box.
On the first keyup the text in the screenshot is "t." This "t" is appended to the message. The result then is "It all started one day t" and the string in the message is now changed to this.
On the next one it's "te" in the text box. But since the string in the message div is "It all started one day t" because of the previous keyup, you now get "It all started one day tte" in the message div.
Etc.
So, yes, it is stacking. One way to deal with this is check in the keyup event for a particular key, like Enter. This way the use can type in the text box and then hit enter and THEN the keyup will perform the append action.
EDIT: Wrong fiddle URL
<nav> does not replace <ul>.
Here's an updated version of what you're using for reference; basically any instance of '#top-menu' has been replaced with 'nav ul'.
Edit: Sorry, forgot to include the link.
It's because you have P tags in the lists, and the buttons and lists are not wrapped by anything. Try this. See that each div of button and list is wrapped and told to float left.
this is probably better solved with css. but since this is a jquery sub, lets solve it with jquery.
you want to put the hover event on the parent of the image and text. http://jsfiddle.net/gf5kq890/1/
hover can still be a bit finicky. you have to work at it to make it not be terrible. css hover can be a bit easier.
If I'm understanding your question correctly, check out the JS in this CodePen. When you click the Alert button, it'll show the text of the item selected in the dropdown.
> Vegas is a jQuery plugin to add beautiful fullscreen backgrounds to your webpages
Maybe it's obvious to others, but I had to go to their Github to figure this out.
While you deserve an upvote on the answer, you should definitely include the "legal disclaimers" ... i.e. arrow functions don't work on IE11, Array.filter() etc. do not exist in IE8 (which is still unfortunately used by some BigCorps and Goverment so depending on target audience - that might be an issue) ... but if those are not an issue, the solution is perfect.
If OP wishes to support IE11 (and couldn't care less about the older browsers) only thing necessary is to change the arrow functions to "old fashioned" lambdas; here the same code annotated:
var unique = originalArray.filter( // Filtering the original array based on the result of this function... function (currentItem, index) { // ...search the index of... return originalArray.indexOf( // ...an item in the original array whose name matches current item... originalArray.find( function (lookupItem) { return lookupItem.name === currentItem.name; } ) ) === index; // ...and if it matches, this is the first time we've seen it (otherwise it is a duplicate) } );
...or - if a one-liner is preferred:
var unique = originalArray.filter(function (currentItem, index) {return originalArray.indexOf(originalArray.find(function(lookupItem){return lookupItem.name === currentItem.name;})) === index;});
You need to add a line which removes the old event handler before assigning a new click function.
gamespace.unbind('click');
Also, you need to set player1turn back to true on player 2's turn.
This is what I started with when I started this haha. This is what I have now.
They are similar, just having a link to each div and an action that hides the previously clicked one.
Thanks for the reply!
Yes, that's it in a nutshell. A year or so back, or more, I guess -- jQuery (and Prototype) both embraced using sizzle to do the selection. As others have said - when you get something by ID
$("#WHAT").attr("href")
It's using the native javascript engine on the browser. When you select with classes, its using javascript code inside jquery (sizzle) to bring you back a collection of elements that match. It's significantly slower.
It's all moot if your app doesn't need to be as performant, but it is definitely good coding practice.
If you think about it -- jQuery is really just a library to normalize the differences between browser compatibilities, with some neat functionality thrown in. So we don't need to worry about coding different AJAX requests, we can just use $.ajax. Things like that. The jQuery library will use native functionality where it can (like getElementById ) to be able to be faster.
http://jsfiddle.net/3kwdgess/15/
I had a little fun and added a "tabs" attribute to your A elements, that targets the ID of what it should be showing. You could flip that back to the HREF if you wanted to.
Basically I've just taken your code and put it into a big if statement. You'll see it's checking if the element you clicked has class of "bk" and if it does, then run your back function, else run the forward function.
There's definitely more that could be done to simplify this. If you start to see things repeating in your code, that's a sign that you might be able to refactor things into one function that can be reused. A lot of people don't write completely efficient code when they start. They'll get it working then go back and refactor the code to make it better.
I added a hasClass check. Bootstrap, while doing the transition, adds the collapsing class to the element. When its done, its removed.
I just added an if statement so that you can't do diddly until its ready to (i.e. the collapsing class is removed).
Will this help?
I added the jquery-ui.js and jquery-ui.css and now it works fine. I think you put in two different versions of css and js and that was causing it to bug or something.
Code-wise .ui-widget-content had url(images/ui-bg_highlight-soft_100_eeeeee_1x100.png) in the background. this was why you had that random box.
So I took a slightly different approach. Assuming that the grid is always square and has the same number of rows as columns (the directions don't specify you have to be able to handle different values), why loop n*n times? Rather, I ran a single loop n times to create an array, then ran a second loop n more times to put a joined copy of the array into a second array. Then final join of the second array gets appended to the DOM.
With the nested loops, a 10x10 grid loops 100 times, but my method only loops 20. However, I'm doing a total of n+1 joins so I'm still creating extra strings that would have to be gc'd.
in a 10x10 situation, I'm not sure how much (if any) improvement this gives. But in a 128x128 situation I'm only looping a total of 256 times instead of 16k times.
I'm not sure how much improvement I'm getting overall though. And honestly, I stumbled across the thread and though "huh, this looks like fun to try" I didn't even know what the Odin Project was. I have no idea if my approach is any good or not. It does work, and it's fairly quick.
I also have a fair bit of extra code around trying to handle margins of the square divs, but that creates some other artifacts that I don't quite understand yet. That could be stripped out
There's a few problems:
Your li elementss are missing a parent ul tag, this is required AFAIK.
Nav is an inline element and those can't be used with slideDown.
And I can only make assumptions about your css.
Here's a working one: https://codepen.io/anon/pen/ERLYoz
Are you trying to fill the squared div with the image fully? Here's a CSS hack for a responsive square div that you'd absolutely position it's child image, centered vertically:
HTML:
<div class="img-container"> <img src="" alt=""> </div>
CSS:
.img-container { width: 100%; padding-top: 100%; overflow: hidden; }
.img-container img { position: absolute; width: 100%; left: 0; top: 50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); }
EDIT: Supports IE9+. Also, I believe this relies on box-sizing: border-box
, which was implemented in Bootstrap 3. If you're using an earlier version, you'll need to add the declarations manually.
We really shouldn't be encouraging this particular effect to be done in pure jquery. This is simply something that should be a css class and transition. The only reason you need jquery is to hit the previous elements.
What is the purpose of the Reset Form
button here? It's almost always a usability mistake. Do you just want to clear the values of one of the cloned username/password/email groups? Is that an operation people will often want to do?
Is this what you were trying to do? http://jsfiddle.net/5x3uK/6/
You need to include "showOn: button" -
$("#date").datepicker({ changeMonth: true, changeYear: true, buttonImage: "images/calendar.png", showOn: "button" });
Here's a fiddle. You can open the console and see the call for the image. http://jsfiddle.net/WD6TU/
I was on my telephone before, so couldn't write code very well ;) I've put together a quick example in jsfiddle, with a little bit of commenting explaining what is happening. I used a regex to do the replace, but I would not do this in production, because you can type any regex into the search box, and get wierd results. Unfortunately, the string.replace method will only replace the first occurance of a string. It should give you a good starting point anyways. http://jsfiddle.net/jeffsmale90/3KPg9/
//create some vars so we don't have to search for //elements every time we want to access them var $select1 = $('select[name=select1]'), $select2 = $('select[name=select2]'), $select3 = $('select[name=select3]');
$select1.change(function() { //default state for $select2 and $select3 is disabled $select2.add($select3).attr('disabled', true);
//enable $select2 and/or $select3 based on $select1's value
switch ($select1.val()) {
case '2':
$select3.attr('disabled', false);
//having no break here means case '1'
applies as well
case '1':
$select2.attr('disabled', false);
break;
}
});
//set an initial state for $select2 and $select3 by firing //$select1's change event $select1.change();
Depending on your values, and how many select boxes there are in total, and your scenario you may wish to swap out the switch
statement for an if...else statement.
Dribbble seems to be using a log scale for this, so that the tags with a lot of items don't completely overshadow the tags with significantly less. Jeff Croft's seems to be linear, though.
/u/thephpjo is right, this is likely something you'd want to do on the server-side. But if you really want to do it in js I've created two really basic scaling functions below. One for a log scale (like Dribbble uses) and one for a linear scale (like Jeff Croft uses). LogScale is dependent on LinearScale, so you'll need both if you want to use LogScale.
var LinearScale = function(){ this.domain = [0, 50]; this.range = [0, 100];
this.scale = function(x){ var point = (x - this.domain[0]) / (this.domain[1] - this.domain[0]); var size = this.range[1] - this.range[0]; return (size * point) + this.range[0]; } };
var LogScale = function(){ this.domain = [0, 1]; this.range = [1, 10];
this.scale = function(x){ var linear = new LinearScale(); linear.domain[0] = Math.log(this.domain[0]); linear.domain[1] = Math.log(this.domain[1]); linear.range = this.range; return linear.scale(Math.log(x)); } };
I'm not really sure about the best way to integrate this as a jQuery plugin as I don't have a whole lot of experience in that area, but you can check out this fiddle, where I've used the function to make something similar to Dribbble's tag bars: http://jsfiddle.net/3S8rH/
Note that my jQuery is probably really terrible. Someone here can probably do it a little nicer.
Scale functions derived from https://github.com/mbostock/d3/
There's a lot of minor mistakes. Also, though it isn't uncommon for this to be called a "slider", the proper UI terminology would be "carousel".
There's a jQuery library out there that is very useful that I would recommend called Owl-Carousel. It's powerful, light, works in all browsers (even IE6, I tested). Easy to use.
I've cleaned up your code, but I don't know enough JS to make it work, just enough to clean up the syntax a little.
Here is a simplified version: http://jsfiddle.net/j9fM3/5/ If I'm understanding correctly, you want to display the image and the text on hover. I set div.info to display:none and used hover, which takes 2 callbacks; on and off. Substitute the fadeIn/Out with whichever animation you want. Also, placehold.it is great for mockups.
Here's a working Jsfiddle. I had to change everything to position:absolute, though.
-edit, cleaned it up and added the fadeTo animation and removed the absolute positioning on your original elements
Glad that it's working!
Let's see if we can figure out the 'why' though:
Try changing those instances of 'jQuery' back to $ and see if it still works. If it does, then it looks like you were just missing the $(function() {}); wrapper code, which is shorthand for $(document).ready(function() {}); This tells jQuery that it should start paying attention to the code inside this block once the document has finished loading.
If it doesn't work after switching back to '$' then you've got a conflict on your site where another javascript library or framework is defining the var '$' as something other than 'jQuery'. The fix for this can be seen on this fiddle.
You just have to add $(document).ready
$(document).ready(function () {
$("#p").click(function(){
$("#p").hide();
});
});
So you've got a parent <tr>, and a child <a>, for example.
If you absolutely must have a click event on the parent (<tr>), then you will want click event handlers for both parent & child.
Once you have a click event handler for the child element, then prevent the event from bubbling up to the parent (event.stopImmediatePropogation()).
Meanwhile, you will still be handling parent click events separately.
Here's an example: https://codepen.io/anon/pen/RLLrxR
sure, any of the above. you can have it create a single json file from the text and image paths. js/ajax is great for when things change: the user clicks a button and it grabs a new set of data. or if you are consuming a third party api/service. for something like this, with mostly static presentation and content, it would probably be better to directly output things on page. here is a list of php filesystem stuff: http://php.net/manual/en/book.filesystem.php if you want to dive in.
the usual issue with something like this is that it is fragile. if the user names a file wrong, or forgets to upload something, or puts it in a different folder... it can break, or behave in weird ways. this is where a CMS would come in.
you can also look at other services which will take care of the file/content management without having a full cms on site. maybe look into using the flickr api https://www.flickr.com/services/api/.
as a general note, moving forward, when asking these types of questions on a technical forum, add what you are looking to do, as well as the question. you may get a correct solution to the stated question, but one that goes down the wrong path for your goal.
A hint for you, never put something like this online without some sort of online demo. 99% of your visitors are NOT going to download it and load up the demo on their own server environment. People want a live demo so they can see what it actually does. Otherwise people will 99% of the time ignore it.
I would suggest using Githubs built-in GH Pages: https://pages.github.com/
The animations in your demo for the dropdowns are too slow. Makes it feel unresponsive.
I also had issues with the dropdown being behind the content https://gyazo.com/7980e5243f745b35912585ca85f30cbc
http://codepen.io/anon/pen/WbjBKp
Here are a few suggestions:
$('#testbox option').size();
will always have the exact same result. So why run it every time the click event is fired? It can just be moved outside the event handler so that it is run once and the result is reused.)couple options:
image processing on the server.
image processing off line.
<div class="imgcontainer"><img src="http://placekitten.com/g/200/300" ></div> .imgcontainer{overflow:hidden;width:120px;height:120px;} .imgcontainer img{width:100%;height:auto;}
something like masonry.js
We use a language called WebSmart to do the server side scripting to update the database records.
Sorry about the confusion. Here is an example of the page. There will also be a change button at the bottom. The choices are pre-populated, but if I change one of them, I need to know if jQuery, or AJAX would recognize something along the lines of:
$("input[@name='Employee 2010']").change(function(){ write sql update statement append to temp file });
Then once the change button is clicked, the script language would be able to read that temp file, and execute the SQL update statements.
Hope that clarifies a bit.
It would be ad-hoc, but sure, it would be just like the one you posted.
I'm not sure if API is the right classification, but you'll definitely be able to wrap the site as you see in the userscript, although you might be better off with something like http://casperjs.org/
Well, I haven't worked with jq mobile yet, but from what I understand it is totally correct to load jquery itself and jquery mobile. ( Check Getting started, there you see them doing this as well)
Did you check if your selector is correct? What happens if you let your button just trigger an alert or something? I also haven't used phonegap, but there's a small item on jq mobile & phonegap here - might be worth a read if you didn't already read it...
It looks like string appending is slightly faster?
http://www.sitepoint.com/javascript-fast-string-concatenation/
Are you saying that javascript just writes a new string to memory every time it appends instead of overwriting the same memory?
That's no problem at all. CSS can help you with a lot of these styling problems. It's good to read up on it just to make sure you're not reinventing the wheel, but keep in mind it suffers from cross compatibility problems. Fortunately there are resources that can keep you ontop of it.
Hey man,
You either need to attach the listener to the parent or rebind after they're loaded.
edit: what /u/thrownaway21 said.
In your method this refers to the function not to the element. If you pass this from the function call, you would pass the event and then you would be able to get the target of the event that way.
However, you should not mix your JS into the html if it can be avoided. The better way to do it with jQuery is to just place an event listener on the table. Look at this code and look at the jsbin link to see how it works. u/MatheusGodoy had a similar approach but this one is an improvement because it only adds one event listener to the table rather than an event listener for every td, which could affect performance with large tables.
$().ready(function () { $('#searchResults').on('click', 'td', function (event) { var id = $(this).closest('tr').attr('id'); console.log(id); alert(id); }); });
http://jsbin.com/rokuliyeta/edit?html,css,js,console,output
Edit: One reason not to mix your JS into the html is because you may change the name of the function or you may need to stop using the click event on the TD. If that happens, you'll have to modify every TD. With the approach I suggested, you can easily modify your program in one place.
You probably want to "sample" color from the input when user click on the "Send" button, not when page initially loads. Is this jsBin close to what you wanted to achieve?
That's great to know. But looking at jQuery.ajax
, followed by jQuery.deferred
I don't see this explicitly mentioned anywhere; even on the Deferred
object documentation. Do you have a source for this info?
Above example functioning as expected in jsBin: http://jsbin.com/qoruqefiwi/edit?js,console
Edit: Found it -- https://api.jquery.com/deferred.always/ For some reason they put the documentation under deferred.always
instead of higher up the tree.
Instead of toggling all items that have the .dropdown-menu class, you want to toggle the one that's a sibling of the 'dropdown-toggle' that was clicked. There are a number of ways to do this, but here's one approach:
Instead of:
$('.dropdown-menu').toggle()
Use:
$(this).next('.dropdown-menu').toggle();
The above leverages $(this) to refer to the .dropdown-toggle element itself that was actually clicked (not all .dropdown-toggle elements) and then finds the .dropdown-menu sibling after it to toggle.
Here's a working example: jsbin.com/wujulodubo
Everything is wrapped iside a $(document).ready(function() { }); event.
In addition to be more specific I'm using $.getJSON to grab the data from a remote API on our server.
It's not pretty but here's a sample.
http://jsbin.com/jawacosonu/1/edit?js
Thanks
For just one pair, you can use an intermediary and chain your .replaces
$('#clickish').html($('#english').val().replace(/t/gi,'XYZXYZ').replace(/s/gi,'t').replace(/XYZXYZ/gi,'s'));
What ebeptonian did makes a better universal solution, though.
Are you able to edit your HTML structure? In that case, try something like this: http://jsbin.com/ejipaz/3/edit#javascript,html,live. I've added a container around the entire post, and given the view and edit DIVs classes that reflect their purpose. Then the click handler becomes simpler - it traverses up to the parent with a class of "post-container" and toggles the display state of any children that have a class of "post".