What is this code's meaning? - javascript

I was designing a webpage and encountered the following code written in javascript I want to know if it's ok if i remove this code and add my own code or does it create any problems Note: This was an code found in an HTML5 Template
Here is the code:
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
var switchery = new Switchery(html);
}

This code selects all HTML elements that have a CSS class of js-switch applied and creates a new Switchery object for each of them. Since you didn't provide much context I have to guess but it's very likely that this will turn standard HTML checkboxes into iOS-style switches.
See also the Switchery homepage for more information: http://abpetkov.github.io/switchery/
Whether this code is needed or not might be a design decision. It'll only change the visual appearance but the sliders still behave like checkboxes. It might, however, be worth checking whether your site actually contains any HTML checkboxes with the js-switch class applied. If not, that code can definitely be dropped.

Related

Custom theme for Payment Request Button [Stripe]

Usually, we use a theme which was provided stripe like the following.
style: {
paymentRequestButton: {
theme: "light-outline"
}
}
They have also provided some theme's like 'dark' | 'light' | 'light-outline'
My question is can we create a custom theme for this button.? eg: a blue colour theme
Or is there any workaround or script hack for changing the color of the button.?
It is not possible to custom style the payment request button. However, you can use Stripe's payment request API with a custom button. The documentation only hints at this. Also, this should still be 100% PCI-compliant, as your application still never sees or touches any credit card information. I have a CodePen you can refer to as an example.
Essentially, just create whatever kind of button you want on your page. Then, bind the click event to paymentRequest.show, where paymentRequest is an instance of Stripe's PaymentRequest. For example:
let stripe = Stripe('pk_test_abc123');
let paymentRequest = stripe.paymentRequest({
...
});
let button = document.getElementById('awesome-custom-button');
button.addEventListener('click', paymentRequest.show);
Then, when you get the token, simply call ev.complete('success') before the end of the delegate function. For example:
paymentRequest.on('token', function (ev) {
// do whatever with the token
ev.complete('success');
});
The only slight hangup is that Apple dictates that the Apple Pay button must be styled a certain way, according to their HIG. The Stripe Elements payment request button handles this out of the box, but since you're no longer using the Elements button with this approach, you simply need to change your custom button manually. There's a number of ways you can do that. In my example code, I'm using Bootstrap and Fontawesome, so in the canMakePayment delegate function:
if (result.applePay) {
button.className = 'btn btn-dark';
button.style.backgroundColor = '#000';
button.querySelector('.default').style.display = 'none';
button.querySelector('.applepay').style.display = 'inline';
}
In my button HTML, I have a span with a "default" class that contains the normal button content and another span with an "applepay" class that is hidden initially and contains the following HTML:
<span class="fa-lg">
<i class="fab fa-apple-pay" data-fa-transform="grow-12"></i>
</span>
<span class="sr-only">Purchase with Apple Pay</span>
I've been trying to do this as well, but the reference docs here at the very bottom seem to indicate the answer is "no".
Looks like beyond a type, and theme the only thing you can set is a height: https://stripe.com/docs/stripe-js/reference#element-options
(Screenshot of relevant section below, in case it changes)
Reading Step 3 of Payment Request Button implementation steps, it is obvious the element has id: #payment-request-button.
Haven't worked with Stripe and I don't know if it's a <button> or a more complex HTML markup structure and I also read somewhere in their docs they do not guarantee maintaining the HTML structure of their elements.
Anyway, here are a few things to keep in mind when aiming this type of intervention: most importantly, develop in steps:
Find a solution that works for the time being. Ideally, it should be something that degrades/fails gracefully and silently (no public facing errors)
Maximize ability to withstand minor modifications in markup from Stripe
Also, keep your source files so you can easily adapt your solution to any markup breaking changes from Stripe so you can provide a fix when it stops working.
If you rely on CSS (recommended), you should inspect the currently rendered markup and find out what are the currently applying selectors. Simply writing stronger selectors should be enough. If styles are being applied via JavaScript by Stripe, chances are you will need to use !important in your CSS. Of course, you should avoid it as much as possible, or at least thoroughly test on as many devices as you can get your hands on.
As a rule of thumb, !important is quite bad in CSS. It's a very powerful hammer and most times it breaks delicate things (i.e.: responsiveness on touch devices).
Alternatively, if you rely on JavaScript to do the styling, you might want to play around with setTimeout() and determine the proper amount of miliseconds to wait before triggering your changes after the prButton.mount() method was called. Test on multiple devices. I advise against this method as it's more error prone and more difficult to control: you want to time your changes just after the element was built but (ideally) before it gets rendered. Of course, there are workarounds, such as hide or fade it until your changes are applied.
Note: This is not an easy task and nobody (except Stripe themselves, by providing a proper method) can guarantee you a bullet-proof solution so I thought laying out the principles on how to approach it might have more value on short and long term than trying to get Stripe working on a test/dev account and provide a particular solution which might stop working the next day, when Stripe change their markup.

Javascript DOM elements hide class and the element not present are same?

I am currently working on a project where most of the code has been written by someone else . I was supposed to do some slight modifications in the existing script to incorporate changes in a new file. I came across a situation where it was very confusing . The scenario is as cited below:
I have an element named as complextabs and it is being used for almost all the pages, except for the one which is being created newly. The situation is there is a code snippet that is written as $('.complextabs').hasClass('.hide'). this incredibly returns the same as when the element complextabs is not even present in the page. Can someone please throw some light on this
And yeah, I am working on Backbone.js . Has this got something to do with the use of Backbone.js
Any suggestion and advice is highly appreciated
Nope, that has nothing to do with the use of Backbone.
Consider the following:
$('.asdasda').hasClass('hide')
This will return false, and it should return false because $('.asdasda') does not return any results. Just running that will yield a JQuery wrapper over an empty list and since there are no elements then obviously there's nothing in there with the css class hide.
If you want to check that there is an element with both the complextabs and the hide class then use $('.complextabs.hide').length.

css3 animation on click

The following zip contains the website html and required files: http://dl.getdropbox.com/u/4281191/login.zip
When you hover the html (html:hover) you see a animation that transforms the container into a loginbox, I want that to happen when I click on "Login" at the "Hello, Guest" menu instead.
Anyway to get this done? I'm new to js...
Additional info:
the css is inside the html,
and the css3 animation gets triggered by:
html:hover id/class {
property: value;
}
Thanks for any help!
And I can't vote at comments since I don't have enough reputation...but I could do some free design work for the person who helps me ^^
I still don't know much about animations, but for what matters here, you could use something like the .classname:active or .classname:focus selectors. But as soon as you click something inside it (e.g. a text box), the style will disappear.
So, for this, it really depends. Do you just want a menu that has links that take the user to another page (for this case, you'll be fine) or do you want a login form (for this case, forget it, use jquery)?
For today and future reference, save this link because it'll be your best friend:
http://www.w3.org/TR/selectors/#selectors
Update
Yes, I hovered but I didn't look at the code. I looked now and, unfortunately, the answer is no. You can't affect some upper level object like that using CSS.
For that use jQuery. The simpler way would be use jQuery to add a class to the element you want to change (like $("#the-object-id").addClass('class-name')). To keep the effect add the duration argument. Read this page about Adding a class using jQuery.

Is there a way to create your own HTML element?

Is there a way to create your own HTML element? I want to make a specially designed check box.
I imagine such a thing would be done in JavaScript. Something akin to document.createHTMLElement but the ability to design your own element (and tag).
No, there isn't.
The HTML elements are limited to what the browser will handle. That is to say, if you created a custom firefox plugin, and then had it handle your special tag, then you "could" do it, for varying interpretations of "doing it". A list of all elements for a particular version of HTML may be found here: http://www.w3.org/TR/html4/index/elements.html
Probably, however, you don't actually want to. If you want to "combine" several existing elements in such a way as they operate together, then you can do that very JavaScript. For example, if you'd like a checkbox to, when clicked, show a dropdown list somewhere, populated with various things, you may do that.
Perhaps you may like to elaborate on what you actually want to achieve, and we can help further.
Yes, you can create your own tags. You have to create a Schema and import it on your page, and write a JavaScript layer to convert your new tags into existing HTML tags.
An example is fbml (Facebook Markup Language), which includes a schema and a JavaScript layer that Facebook wrote. See this: Open Graph protocol.
Using it you can make a like button really easily:
<fb:like href="http://developers.facebook.com/" width="450" height="80"/>
The easiest way would be probably to write a plugin say in Jquery (or Dojo, MooTools, pick one).
In case of jQuery you can find some plugins here http://plugins.jquery.com/ and use them as a sample.
You need to write own doctype or/and use own namespace to do this.
http://msdn.microsoft.com/en-us/magazine/cc301515.aspx
No, there is not. Moreover it is not allowed in HTML5.
Take a look at Ample SDK JavaScript GUI library that enables any custom elements or event namespaces client-side (this way XUL for example was implemented there) without interferring with the rules of HTML5.
Take a look into for example how XUL scale element implemented: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/elements/scale.js and its default stylesheet: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/themes/default/input.css
It's a valid question, but I think the name of the game from the UI side is progressive markup. Build out valid w3 compliant tags and then style them appropriately with javascript (in my case Jquery or Dojo) and CSS. A well-written block of CSS can be reused over and over (my favorite case is Jquery UI with themeroller) and style nearly any element on the page with just a one or two-word addition to the class declaration.
Here's some good Jquery/Javascript/CSS solutions that are relatively simple:
http://www.filamentgroup.com/examples/customInput/
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
Here's the spec for the upcoming (and promising) JqueryUI update for form elements:http://wiki.jqueryui.com/Checkbox
If you needed to validate input, this is an easy way to get inline validation with a single class or id tag: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Ok, so my solution isn't a 10 character, one line solution. However, Jquery Code aside, each individual tag wouldn't be much more than:
<input type="checkbox" id="theid">
So, while there would be a medium chunk of Jquery code, the individual elements would be very small, which is important if you're repeating it 250 times (programmatically) as my last project required. It's easy to code, degrades well, validates well, and because progressive markup would be on the user's end, have virtually no cost on the server end.
My current project is in Symfony--not my choice--which uses complex, bulky server-side tags to render form elements, validate, do javascript onclick, style, etc. This seems like what you were asking for at first....and let me tell you, it's CLUNKY. One tag to call a link can be 10 lines of code long! After being forced to do it, I'm not a fan.
Hm. The first thought is that you could create your own element and do a transformation with XSLT to the valid HTML then.
With the emergence of the emerging W3 Web Components standard, specifically the Custom Elements spec, you can now create your own custom HTML elements and register them with the parser with the document.register() DOM method.
X-Tag is a helpful sugar library, developed by Mozilla, that makes it even easier to work with Web Components, have a look: X-Tags.org

How to reorder a row of html input fields without getting into AJAX

I'm generating a set of rows of html input text fields, which I want my end-users to be able to reorder. I don't want to use AJAX, but am okay with Javascript.
I'm okay with some arrow buttons placed on the side of each row, which when pressed move the fields up and down.
My issue with AJAX is that its too heavy (50-60kb) for just this functionality. I had a look at some Yahoo code (YUI), but again, it seems overkill for one particular functionality. I found this - http://www.danvk.org/wp/dragtable/ - which is seems like the lightest code, but only allows column reordering.
I'll be working on the last option, but I'm open to other thoughts / approaches on how to do this (ie, to allow the user to reorder the row-wise fields).
PS: Not important to this discussion I suppose, but I'm using PHP to generate these html text fields.
Adding to the Josef's answer...
According to W3C DOM Level 2 Core specification:
insertBefore
Inserts the node newChild before the existing child node refChild. [...]
If the newChild is already in the tree, it is first removed.
Thus, there is no need to call removeChild() before calling insertChild().
Also, IE6 DOM support is very bad, so you might need to write specific code for it. Or maybe you would prefer to not waste time supporting this browser, and ask users to upgrade. Or, if you really need to support IE6, maybe using a JavaScript library (like jQuery) could be an easy solution.
Edit: This is the final JavaScript solution, based on Josef's answer:
function up(row) {
var prevRow = row.previousSibling;
if(prevRow) {
row.parentNode.insertBefore(row, prevRow);
}
}
You can write a javascript function similar to this one
function up(row) {
var prevRow = row.previousElementSibling;
if(prevRow != null) {
row.parentNode.removeChild(row);
document.body.insertBefore(row, prevRow);
}
};
and use it in your rows like this:
<p>
<input type="text"/>
<a onclick="up(this.parentNode)">Up</a>
</p>
I agree with you that you don't really need to reference a Javascript framework for a very simple task like this.
You seem to be confused; AJAX is a general term referring to using Javascript to load extra content from a server via sub-requests without actually loading a new page. There are many different Javascript libraries that can handle AJAX requests.
Perhaps you're thinking of one of the more popular libraries like JQuery when you say "AJAX"?
As for your question - one thing to remember is that with proper server configuration, client browsers will general cache Javascript libraries after the first request; thus the consistent overall load time isn't as impacted by the size of such libraries - only that first page load. You can avoid even that if you use the Google-hosted copy of JQuery, which is likely to already be cached by the large majority of visitors to your site.

Categories