Monday, April 24, 2017
Data Access Object (DAO)
# The Data Access Object (DAO) support in Spring is aimed at making it easy to
Views - SQL
Benifits of Views
A view provides several benefits.
1. Views can hide complexity
If you have a query that requires joining several tables, or has complex logic or calculations,
you can code all that logic into a view, then select from the view just like you would a table.
2. Views can be used as a security mechanism
A view can select certain columns and/or rows from a table, and permissions set on the view
instead of the underlying tables. This allows surfacing only the data that a user needs to see.
3. Views can simplify supporting legacy code
If you need to refactor a table that would break a lot of code, you can replace the table
with a view of the same name. The view provides the exact same schema as the original table,
while the actual schema has changed. This keeps the legacy code that references the table
from breaking, allowing you to change the legacy code at your leisure.
4.Among other things, it can be used for security. If you have a "customer" table, you might
want to give all of your sales people access to the name, address, zipcode, etc. fields, but
not credit_card_number. You can create a view that only includes the columns they need access
to and then grant them access on the view.
5.A view is an encapsulation of a query. Queries that are turned into views tend to be complicated
and as such saving them as a view for reuse can be advantageous. Though a view doesn't store data, some refer to a views as “virtual tables,” you can query a view like you can a table .
6.Once a view is created you can used then as you would any table in a SELECT statement.
7.Views take up very little space, as the data is stored once in the source table.
Sample view is shown below .
CREATE OR REPLACE VIEW SAMPLE_VIEW AS
SELECT cast('A' as varchar2(2)) col1,'Overdue period > 0 month and < 3 months' col2
FROM dual
UNION
SELECT cast('B' as varchar2(2)) col1,'Overdue period > 3 month and < 6 months' col2
FROM dual
UNION
SELECT cast('C' as varchar2(2)) col1,'Overdue period >= 24 months' col2
FROM dual
UNION
SELECT cast('D' as varchar2(2)) col1, 'Overdue RV > 0' col2
FROM dual
Friday, April 7, 2017
Saturday, April 1, 2017
How to Rock a Side Project When You Have No Free Time (Extracted From StackOverflow ,Author Alyssa Mazzina)
We’ve all heard the advice: the best
developers live and breathe programming. But you’re also a human being.
Maybe you’re not the stereotypical 22-year-old with no ties or
responsibilities, happy to work 18-hour days. Maybe you’re a mother or a
father, a husband or a wife, a caretaker of an elderly relative.
There are millions of developers in the world, and they come in every shape. Most of us are not in our early 20s, many of us aren’t single, and few of us want to give our entire lives to our jobs. So how do we reconcile that truth with the general belief that the “best” developers are those who eat, sleep, and breathe code?
In other words, how can you show you’re passionate and committed without completely neglecting the rest of your life and responsibilities? Specifically, how can you find the time for personal projects without losing your mind?
I spoke with a few developers who face this challenge every day. These are people with full-time jobs, families, and busy non-work lives who have also built and continue to build successful side projects. There’s no magic bullet, they insist. It’s a matter of priorities and accountability. Here’s how they do it without destroying their lives in the process.
Developer Neil Harris built Intently.co as a side project while also working full-time as tech lead for a UK engineering company. Intently.co is growing quickly, and he expects it to become a full-time venture soon, but he maintains that building it “on the side” was of great value. “I wanted to build something without any investment, and this was the best way—my job gives me the financial stability to try new ventures on the side.”
Neil adds that it’s opened doors in his career. “I am now much more adept and confident with web technologies than I was before, and this gives me the confidence to lead teams in this space at work. Perhaps the most exciting opportunity is the chance to advise other startups or companies who want to grow their web presence—I have learnt a huge amount about hosting, SEO, and web apps because I have made a success of Intently.co, and I think it gives me the credentials to go and advise other companies.”
Stephan Baker, a software engineer at Forest Giant, agrees: “I don’t really go into these projects expecting it to open doors, but without a doubt it has on many occasions. Side projects, as well as attending developer events such as meetups and conferences, can really help to grow your professional network. Finding other people who are excited about the things you are excited about opens many doors, both personally and professionally.”
Justin Avdich, a Web Developer at Cheeky Monkey Media, says his side project is a passion project, and notes the benefits of building a reputation. It “helps me learn new skills and stay on top of some of the trends,” he says. “It’s also a way for me to put my work out in the wild for people to see.”
We’ve written before about building reputation and getting your work out there for people to see, and the developers I talked to agreed that side projects are an ideal way to do that. “Most technology jobs like people who have side projects,” says Max. “It shows you don’t just mail it in 9-5. You actually enjoy pushing yourself and using new technology. It shows passion.”
Unfortunately, some employers equate “you’re passionate about coding” with “you code in your free time.” While this is unfair assumption, developers who do have a side project can use it as a tangible and demonstrable example of loving their craft.
Adam Richardson of Forest Giant agrees. “I think it’s crucial to try to keep the job fun. Maybe what you’re working on at your day job isn’t your favorite and you feel totally drained once you’re done. This is understandable, but I think a powerful tool to fight burnout is continually seeking out, independently, things you find exciting and interesting.”

Doug Bradley, owner of Inland Empire Lawyers (which he built on the side while working full-time as a software developer for another firm), stresses the importance of being realistic. “Anyone that thinks building a side business is something you can do in your spare time is kidding themselves. There’s no such thing as spare time.” Rather, he argues, you can find the time if you’re truly passionate about something by prioritizing that over other things. “If you have no passion for it, then you’ll find no value or sense of pride trading your personal and family time to develop it properly.” Watching TV was the most commonly cited activity that developers forego in favor of coding.
Liza, raising four children with a husband in the military who is gone often, says, “I schedule every aspect of my life in order to create time for everything. I hire in-home childcare and household cleaning to help maximize my time. Everything in my life functions according to a plan. Laundry, groceries, family play time and work all get a schedule.”
Craig is blunt: “Replace ‘I don’t have time for this’ with ‘This isn’t a priority for me.’ Anyone can make time for something if it’s a priority… stop talking about it and start making it.”
One technique developers cite for “making” or “finding” time is setting aside a block of time—even a very small one—every day and holding yourself accountable. Milen Marinov, Lead Mobile Developer at Kanbanize, has built an app on the side called Help A Paw that “helps volunteers coordinate their efforts in helping injured stray animals.” Milen reminds us, “We all get 24 hours every day and having the time to do something is just a matter of priorities. So, if you feel your contribution will really help make other people’s (or animals’) lives better, you’ll find the time to do it!”
Overall, these developers felt that finding time to work on side projects wasn’t as difficult as many of us think it will be. Finding something you’re passionate about, holding yourself accountable, and scheduling hard blocks of time that you’re committed to spending on your project will all help you make progress on a side project.

Ethan Schmidt, who built GymBull.com with friends while working full-time as a software developer for the Department of Defense, agrees. “Don’t wait until you’re 100% comfortable with either technology or your business idea because by the time that you are, someone else will have made what you want and the whole community will be using a different set of tools.”
Neil says, “Jump in—if you have an idea then you can build it.” And Max advises finding a problem that people have (preferably all people, not just other developers, he emphasizes). Next, you should build “a small solution in a weekend and push it out live. Once something is live usually people find small amounts of time to incrementally make it better. Just take that first step, and it’s easier to keep going.”
This is also a way you can get involved and show your passion without diving in fully to building an entire product on your own. Just getting your feet wet by helping with somebody else’s project is a good start, and for some developers, that’s enough side work to keep their skills fresh and their network growing. Even if you don’t have a Big Idea, there is work to be done that you can do. And then you can put it on your resume.
Julia Silge, a Data Scientist here at Stack Overflow, told me that getting involved in open source helped her transition into data science after spending a few years caring for her children full-time. “I got involved in open source thinking I would learn and update my skills,” she says, “but the network I’ve built has been invaluable to my career.”
Don’t waste what little time you have on things that aren’t worth the sacrifice; chances are, you have plenty of those things in your life, sucking up minutes here and there. A little discipline and prioritizing can help you make those minutes productive and rewarding.

Liza says, “I have a passion to see other professional women balance their families and continue their careers.” This passion drives her to find the time, and she finds it rewarding. “If I can juggle two jobs, four kids, and a husband in the military that’s gone all the time, the sky’s the limit.”
Craig, who is married with two young children, acknowledges the difficulties in balancing his priorities. “I pick up the kids from school every day, and cook dinner for my family,” he says. “And client work always takes priority over side projects. Yet, I’ve been able to build and launch a number of side projects.” He works late at night, when the kids are asleep, and gives himself strict deadlines. “It’s important to do a little bit each day,” he says, “even if it’s just an hour.”
He also acknowledges the importance of a supportive partner. “Having a partner’s support can be incredibly encouraging,” he says, noting that he can bounce ideas off his wife for feedback. “It’s important to make sure [your work] doesn’t infringe upon your personal relationships or family obligations…Friday and Saturday nights, there’s a no-work policy in our house.”
Justin’s wife, too, supports his efforts. “Without her support, it wouldn’t really be possible. I feel it’s important for a relationship to spend time doing things we both enjoy (sometimes it’s something together, sometimes it’s something individual).”
“Building and launching your own product can be an incredibly fulfilling experience,” says Craig. “And once you launch your first side project, you’ll be back for more.”
Craig says he has a policy of “Funday Fridays, where everyone is allowed to work on their own side projects. Of course, if there’s a deadline for client work, that takes precedence, but having that day informally set aside to work on personal projects allows for an extended period of serious progress each week.” You might be surprised how many companies will allow some of this. But of course, many do not, and expect you to be on task for 40 hours per week, no exceptions. If this is the type of company you work for, don’t cross any lines.
You should also be aware that some contracts include clauses stipulating that if you DO build anything on company time, the company then owns the result (and any profit that comes from it). See what Stack Overflow CEO Joel Spolsky has to say about this.
The developers I talked to all agreed it is possible to find legitimate “free” time, even in the busiest lives, if you prioritize that time—and you shouldn’t have to short-change your employer to do it.
Link to Original Post :-
There are millions of developers in the world, and they come in every shape. Most of us are not in our early 20s, many of us aren’t single, and few of us want to give our entire lives to our jobs. So how do we reconcile that truth with the general belief that the “best” developers are those who eat, sleep, and breathe code?
In other words, how can you show you’re passionate and committed without completely neglecting the rest of your life and responsibilities? Specifically, how can you find the time for personal projects without losing your mind?
I spoke with a few developers who face this challenge every day. These are people with full-time jobs, families, and busy non-work lives who have also built and continue to build successful side projects. There’s no magic bullet, they insist. It’s a matter of priorities and accountability. Here’s how they do it without destroying their lives in the process.
Why do developers build on the side?
Keeping skills sharp
Max Page, a lead developer turned product manager, values the opportunity to work on his side project CouponHippo because it helps him keep his coding skills fresh now that he’s not using them like he used to in his day job. “My main goals for this work,” he says, “are to keep my coding skills sharp, play with new technologies that come out, and to augment my normal income if possible.”Additional income
A secondary income stream is a driving factor for many developers who work on personal projects outside of work. Craig Phares runs his own digital agency, Six Overground, full time, but also works on smaller projects (here’s one example) outside the scope of his client work. “As a digital agency,” he says, “we’re often tied very closely to an hourly rate, so to make more money you have to work more hours. Building a product that brings in revenue without a direct relation to hours is ideal and fills in those inevitable slow periods of client work.”New technologies, new opportunities
Craig also values the non-monetary benefits of side work. “Side projects are a great opportunity to learn a new technology. My first Ruby on Rails web application was a side project. My first native mobile app was a side project. Because you have the luxury of taking the time to experiment, you can really advance your technical chops.”Developer Neil Harris built Intently.co as a side project while also working full-time as tech lead for a UK engineering company. Intently.co is growing quickly, and he expects it to become a full-time venture soon, but he maintains that building it “on the side” was of great value. “I wanted to build something without any investment, and this was the best way—my job gives me the financial stability to try new ventures on the side.”
Neil adds that it’s opened doors in his career. “I am now much more adept and confident with web technologies than I was before, and this gives me the confidence to lead teams in this space at work. Perhaps the most exciting opportunity is the chance to advise other startups or companies who want to grow their web presence—I have learnt a huge amount about hosting, SEO, and web apps because I have made a success of Intently.co, and I think it gives me the credentials to go and advise other companies.”
Stephan Baker, a software engineer at Forest Giant, agrees: “I don’t really go into these projects expecting it to open doors, but without a doubt it has on many occasions. Side projects, as well as attending developer events such as meetups and conferences, can really help to grow your professional network. Finding other people who are excited about the things you are excited about opens many doors, both personally and professionally.”
Justin Avdich, a Web Developer at Cheeky Monkey Media, says his side project is a passion project, and notes the benefits of building a reputation. It “helps me learn new skills and stay on top of some of the trends,” he says. “It’s also a way for me to put my work out in the wild for people to see.”
We’ve written before about building reputation and getting your work out there for people to see, and the developers I talked to agreed that side projects are an ideal way to do that. “Most technology jobs like people who have side projects,” says Max. “It shows you don’t just mail it in 9-5. You actually enjoy pushing yourself and using new technology. It shows passion.”
Passion
Passion is a main driver of side projects, and often times that passion comes from wanting to address a roadblock you’ve stumbled across in your daily life. Liza Rodewald, a .NET developer for the Mississippi Secretary of State’s office, cofounded a company called MadSkills on the side to fix a difficult issue she experienced: “I starting working on this project to solve a business problem I came across as a military spouse. There were professional spouses struggling to find meaningful professional work due to the frequent moves required by the military. MadSkills is my passion project.”Unfortunately, some employers equate “you’re passionate about coding” with “you code in your free time.” While this is unfair assumption, developers who do have a side project can use it as a tangible and demonstrable example of loving their craft.
How do they find the time?
Keep it fun
In fact, passion was a recurring theme with the developers I spoke with. Most of them, when asked how they find or make time for side projects while they’re working full-time, raising families, or fulfilling other obligations, cite passion before anything else. Justin, who has both a full-time job and a 10-month-old daughter, says, “I feel that if you’re passionate about something, and enjoy doing it, it becomes easy to find the time. I treat it as a hobby, more of an escape than actual work.”Adam Richardson of Forest Giant agrees. “I think it’s crucial to try to keep the job fun. Maybe what you’re working on at your day job isn’t your favorite and you feel totally drained once you’re done. This is understandable, but I think a powerful tool to fight burnout is continually seeking out, independently, things you find exciting and interesting.”
Prioritize and schedule

Doug Bradley, owner of Inland Empire Lawyers (which he built on the side while working full-time as a software developer for another firm), stresses the importance of being realistic. “Anyone that thinks building a side business is something you can do in your spare time is kidding themselves. There’s no such thing as spare time.” Rather, he argues, you can find the time if you’re truly passionate about something by prioritizing that over other things. “If you have no passion for it, then you’ll find no value or sense of pride trading your personal and family time to develop it properly.” Watching TV was the most commonly cited activity that developers forego in favor of coding.
Liza, raising four children with a husband in the military who is gone often, says, “I schedule every aspect of my life in order to create time for everything. I hire in-home childcare and household cleaning to help maximize my time. Everything in my life functions according to a plan. Laundry, groceries, family play time and work all get a schedule.”
Craig is blunt: “Replace ‘I don’t have time for this’ with ‘This isn’t a priority for me.’ Anyone can make time for something if it’s a priority… stop talking about it and start making it.”
One technique developers cite for “making” or “finding” time is setting aside a block of time—even a very small one—every day and holding yourself accountable. Milen Marinov, Lead Mobile Developer at Kanbanize, has built an app on the side called Help A Paw that “helps volunteers coordinate their efforts in helping injured stray animals.” Milen reminds us, “We all get 24 hours every day and having the time to do something is just a matter of priorities. So, if you feel your contribution will really help make other people’s (or animals’) lives better, you’ll find the time to do it!”
Overall, these developers felt that finding time to work on side projects wasn’t as difficult as many of us think it will be. Finding something you’re passionate about, holding yourself accountable, and scheduling hard blocks of time that you’re committed to spending on your project will all help you make progress on a side project.
Ship it. Now.
Most of the developers I spoke with stressed the importance of just shipping. Stephan says, “Whatever it is you’re making, remember that development is an iterative process. What you are making doesn’t have to be perfect the first time through, it isn’t going to be everyone’s cup of tea, and you shouldn’t wait until it’s finished to show someone what you’ve been doing (hint: It’s never really finished.”
Ethan Schmidt, who built GymBull.com with friends while working full-time as a software developer for the Department of Defense, agrees. “Don’t wait until you’re 100% comfortable with either technology or your business idea because by the time that you are, someone else will have made what you want and the whole community will be using a different set of tools.”
Neil says, “Jump in—if you have an idea then you can build it.” And Max advises finding a problem that people have (preferably all people, not just other developers, he emphasizes). Next, you should build “a small solution in a weekend and push it out live. Once something is live usually people find small amounts of time to incrementally make it better. Just take that first step, and it’s easier to keep going.”
Don’t forget about open source
Jesse Lucas, CTO of Forest Giant, advocates dabbling in the open source world, something we’ve also mentioned before here. “Don’t wait to be asked to help or join,” he advises. “Find something you’re interested in and start helping. The open source community is extremely helpful and inclusive. Don’t be afraid to put yourself out there and start contributing!”This is also a way you can get involved and show your passion without diving in fully to building an entire product on your own. Just getting your feet wet by helping with somebody else’s project is a good start, and for some developers, that’s enough side work to keep their skills fresh and their network growing. Even if you don’t have a Big Idea, there is work to be done that you can do. And then you can put it on your resume.
Is it worth the sacrifices?
All of the developers I talked to about this felt strongly that working on side projects had benefited their careers and their lives; none of them regretted the time they’d spent on their projects. They all have full-time jobs, and most have spouses, children, and other obligations, but they all maintain that prioritizing a side project, starting small, and keeping the work fun help them push forward and accomplish great things “on the side.”Julia Silge, a Data Scientist here at Stack Overflow, told me that getting involved in open source helped her transition into data science after spending a few years caring for her children full-time. “I got involved in open source thinking I would learn and update my skills,” she says, “but the network I’ve built has been invaluable to my career.”
Don’t waste what little time you have on things that aren’t worth the sacrifice; chances are, you have plenty of those things in your life, sucking up minutes here and there. A little discipline and prioritizing can help you make those minutes productive and rewarding.

Liza says, “I have a passion to see other professional women balance their families and continue their careers.” This passion drives her to find the time, and she finds it rewarding. “If I can juggle two jobs, four kids, and a husband in the military that’s gone all the time, the sky’s the limit.”
Craig, who is married with two young children, acknowledges the difficulties in balancing his priorities. “I pick up the kids from school every day, and cook dinner for my family,” he says. “And client work always takes priority over side projects. Yet, I’ve been able to build and launch a number of side projects.” He works late at night, when the kids are asleep, and gives himself strict deadlines. “It’s important to do a little bit each day,” he says, “even if it’s just an hour.”
He also acknowledges the importance of a supportive partner. “Having a partner’s support can be incredibly encouraging,” he says, noting that he can bounce ideas off his wife for feedback. “It’s important to make sure [your work] doesn’t infringe upon your personal relationships or family obligations…Friday and Saturday nights, there’s a no-work policy in our house.”
Justin’s wife, too, supports his efforts. “Without her support, it wouldn’t really be possible. I feel it’s important for a relationship to spend time doing things we both enjoy (sometimes it’s something together, sometimes it’s something individual).”
“Building and launching your own product can be an incredibly fulfilling experience,” says Craig. “And once you launch your first side project, you’ll be back for more.”
A word of caution
One thing the developers I spoke to agreed on was the importance of keeping your employer’s time and your own time separate. If you’re doing work on the side, it must actually be on the side—not snuck in at the office, or done when you should be working for a client.Craig says he has a policy of “Funday Fridays, where everyone is allowed to work on their own side projects. Of course, if there’s a deadline for client work, that takes precedence, but having that day informally set aside to work on personal projects allows for an extended period of serious progress each week.” You might be surprised how many companies will allow some of this. But of course, many do not, and expect you to be on task for 40 hours per week, no exceptions. If this is the type of company you work for, don’t cross any lines.
You should also be aware that some contracts include clauses stipulating that if you DO build anything on company time, the company then owns the result (and any profit that comes from it). See what Stack Overflow CEO Joel Spolsky has to say about this.
The developers I talked to all agreed it is possible to find legitimate “free” time, even in the busiest lives, if you prioritize that time—and you shouldn’t have to short-change your employer to do it.
Your turn
I’d love to hear from you, the reader: do you have a side project? If not, why not? And what other information on side projects can I bring you to help you succeedLink to Original Post :-
How to Rock a Side Project When You Have No Free Time By Alyssa Mazzina
Comments in Different Programming Languages
#Java
// single line comment
/*
multiple
line
comment
*/
#JavaScript
#JSP
<%-- comment --%>
#HTML
<!-- comment -->
#SQL
--comment
Thursday, March 23, 2017
HTML DOM Events
HTML DOM Events
HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document.Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).
Tip: The event model was standardized by the W3C in DOM Level 2.
HTML DOM Events
DOM: Indicates in which DOM Level the property was introduced.
Mouse Events
| Event | Description | DOM |
|---|---|---|
| onclick | The event occurs when the user clicks on an element | 2 |
| oncontextmenu | The event occurs when the user right-clicks on an element to open a context menu | 3 |
| ondblclick | The event occurs when the user double-clicks on an element | 2 |
| onmousedown | The event occurs when the user presses a mouse button over an element | 2 |
| onmouseenter | The event occurs when the pointer is moved onto an element | 2 |
| onmouseleave | The event occurs when the pointer is moved out of an element | 2 |
| onmousemove | The event occurs when the pointer is moving while it is over an element | 2 |
| onmouseover | The event occurs when the pointer is moved onto an element, or onto one of its children | 2 |
| onmouseout | The event occurs when a user moves the mouse pointer out of an element, or out of one of its children | 2 |
| onmouseup | The event occurs when a user releases a mouse button over an element | 2 |
Keyboard Events
| Event | Description | DOM |
|---|---|---|
| onkeydown | The event occurs when the user is pressing a key | 2 |
| onkeypress | The event occurs when the user presses a key | 2 |
| onkeyup | The event occurs when the user releases a key | 2 |
Frame/Object Events
| Event | Description | DOM |
|---|---|---|
| onabort | The event occurs when the loading of a resource has been aborted | 2 |
| onbeforeunload | The event occurs before the document is about to be unloaded | 2 |
| onerror | The event occurs when an error occurs while loading an external file | 2 |
| onhashchange | The event occurs when there has been changes to the anchor part of a URL | 3 |
| onload | The event occurs when an object has loaded | 2 |
| onpageshow | The event occurs when the user navigates to a webpage | 3 |
| onpagehide | The event occurs when the user navigates away from a webpage | 3 |
| onresize | The event occurs when the document view is resized | 2 |
| onscroll | The event occurs when an element's scrollbar is being scrolled | 2 |
| onunload | The event occurs once a page has unloaded (for <body>) | 2 |
Form Events
| Event | Description | DOM |
|---|---|---|
| onblur | The event occurs when an element loses focus | 2 |
| onchange | The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <keygen>, <select>, and <textarea>) | 2 |
| onfocus | The event occurs when an element gets focus | 2 |
| onfocusin | The event occurs when an element is about to get focus | 2 |
| onfocusout | The event occurs when an element is about to lose focus | 2 |
| oninput | The event occurs when an element gets user input | 3 |
| oninvalid | The event occurs when an element is invalid | 3 |
| onreset | The event occurs when a form is reset | 2 |
| onsearch | The event occurs when the user writes something in a search field (for <input="search">) | 3 |
| onselect | The event occurs after the user selects some text (for <input> and <textarea>) | 2 |
| onsubmit | The event occurs when a form is submitted | 2 |
Drag Events
| Event | Description | DOM |
|---|---|---|
| ondrag | The event occurs when an element is being dragged | 3 |
| ondragend | The event occurs when the user has finished dragging an element | 3 |
| ondragenter | The event occurs when the dragged element enters the drop target | 3 |
| ondragleave | The event occurs when the dragged element leaves the drop target | 3 |
| ondragover | The event occurs when the dragged element is over the drop target | 3 |
| ondragstart | The event occurs when the user starts to drag an element | 3 |
| ondrop | The event occurs when the dragged element is dropped on the drop target | 3 |
Clipboard Events
| Event | Description | DOM |
|---|---|---|
| oncopy | The event occurs when the user copies the content of an element | |
| oncut | The event occurs when the user cuts the content of an element | |
| onpaste | The event occurs when the user pastes some content in an element |
Print Events
| Event | Description | DOM |
|---|---|---|
| onafterprint | The event occurs when a page has started printing, or if the print dialogue box has been closed | 3 |
| onbeforeprint | The event occurs when a page is about to be printed | 3 |
Media Events
| Event | Description | DOM |
|---|---|---|
| onabort | The event occurs when the loading of a media is aborted | 3 |
| oncanplay | The event occurs when the browser can start playing the media (when it has buffered enough to begin) | 3 |
| oncanplaythrough | The event occurs when the browser can play through the media without stopping for buffering | 3 |
| ondurationchange | The event occurs when the duration of the media is changed | 3 |
| onemptied | The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects) | 3 |
| onended | The event occurs when the media has reach the end (useful for messages like "thanks for listening") | 3 |
| onerror | The event occurs when an error occurred during the loading of a media file | 3 |
| onloadeddata | The event occurs when media data is loaded | 3 |
| onloadedmetadata | The event occurs when meta data (like dimensions and duration) are loaded | 3 |
| onloadstart | The event occurs when the browser starts looking for the specified media | 3 |
| onpause | The event occurs when the media is paused either by the user or programmatically | 3 |
| onplay | The event occurs when the media has been started or is no longer paused | 3 |
| onplaying | The event occurs when the media is playing after having been paused or stopped for buffering | 3 |
| onprogress | The event occurs when the browser is in the process of getting the media data (downloading the media) | 3 |
| onratechange | The event occurs when the playing speed of the media is changed | 3 |
| onseeked | The event occurs when the user is finished moving/skipping to a new position in the media | 3 |
| onseeking | The event occurs when the user starts moving/skipping to a new position in the media | 3 |
| onstalled | The event occurs when the browser is trying to get media data, but data is not available | 3 |
| onsuspend | The event occurs when the browser is intentionally not getting media data | 3 |
| ontimeupdate | The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media) | 3 |
| onvolumechange | The event occurs when the volume of the media has changed (includes setting the volume to "mute") | 3 |
| onwaiting | The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data) | 3 |
Animation Events
| Event | Description | DOM |
|---|---|---|
| animationend | The event occurs when a CSS animation has completed | 3 |
| animationiteration | The event occurs when a CSS animation is repeated | 3 |
| animationstart | The event occurs when a CSS animation has started | 3 |
Transition Events
| Event | Description | DOM |
|---|---|---|
| transitionend | The event occurs when a CSS transition has completed | 3 |
Server-Sent Events
| Event | Description | DOM |
|---|---|---|
| onerror | The event occurs when an error occurs with the event source | |
| onmessage | The event occurs when a message is received through the event source | |
| onopen | The event occurs when a connection with the event source is opened |
Misc Events
| Event | Description | DOM |
|---|---|---|
| onmessage | The event occurs when a message is received through or from an object (WebSocket, Web Worker, Event Source or a child frame or a parent window) | 3 |
| onmousewheel | Deprecated. Use the onwheel event instead | |
| ononline | The event occurs when the browser starts to work online | 3 |
| onoffline | The event occurs when the browser starts to work offline | 3 |
| onpopstate | The event occurs when the window's history changes | 3 |
| onshow | The event occurs when a <menu> element is shown as a context menu | 3 |
| onstorage | The event occurs when a Web Storage area is updated | 3 |
| ontoggle | The event occurs when the user opens or closes the <details> element | 3 |
| onwheel | The event occurs when the mouse wheel rolls up or down over an element | 3 |
Touch Events
| Event | Description | DOM |
|---|---|---|
| ontouchcancel | The event occurs when the touch is interrupted | |
| ontouchend | The event occurs when a finger is removed from a touch screen | |
| ontouchmove | The event occurs when a finger is dragged across the screen | |
| ontouchstart | The event occurs when a finger is placed on a touch screen |
Event Object
Constants
| Constant | Description | DOM |
|---|---|---|
| CAPTURING_PHASE | The current event phase is the capture phase (1) | 1 |
| AT_TARGET | The current event is in the target phase, i.e. it is being evaluated at the event target (2) | 2 |
| BUBBLING_PHASE | The current event phase is the bubbling phase (3) | 3 |
Properties
| Property | Description | DOM |
|---|---|---|
| bubbles | Returns whether or not a specific event is a bubbling event | 2 |
| cancelable | Returns whether or not an event can have its default action prevented | 2 |
| currentTarget | Returns the element whose event listeners triggered the event | 2 |
| defaultPrevented | Returns whether or not the preventDefault() method was called for the event | 3 |
| eventPhase | Returns which phase of the event flow is currently being evaluated | 2 |
| isTrusted | Returns whether or not an event is trusted | 3 |
| target | Returns the element that triggered the event | 2 |
| timeStamp | Returns the time (in milliseconds relative to the epoch) at which the event was created | 2 |
| type | Returns the name of the event | 2 |
| view | Returns a reference to the Window object where the event occured | 2 |
Methods
| Method | Description | DOM |
|---|---|---|
| preventDefault() | Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur | 2 |
| stopImmediatePropagation() | Prevents other listeners of the same event from being called | 3 |
| stopPropagation() | Prevents further propagation of an event during event flow | 2 |
MouseEvent Object
| Property | Description | DOM |
|---|---|---|
| altKey | Returns whether the "ALT" key was pressed when the mouse event was triggered | 2 |
| button | Returns which mouse button was pressed when the mouse event was triggered | 2 |
| buttons | Returns which mouse buttons were pressed when the mouse event was triggered | 3 |
| clientX | Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered | 2 |
| clientY | Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered | 2 |
| ctrlKey | Returns whether the "CTRL" key was pressed when the mouse event was triggered | 2 |
| detail | Returns a number that indicates how many times the mouse was clicked | 2 |
| metaKey | Returns whether the "META" key was pressed when an event was triggered | 2 |
| pageX | Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered | |
| pageY | Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered | |
| relatedTarget | Returns the element related to the element that triggered the mouse event | 2 |
| screenX | Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered | 2 |
| screenY | Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered | 2 |
| shiftKey | Returns whether the "SHIFT" key was pressed when an event was triggered | 2 |
| which | Returns which mouse button was pressed when the mouse event was triggered | 2 |
KeyboardEvent Object
| Property | Description | DOM |
|---|---|---|
| altKey | Returns whether the "ALT" key was pressed when the key event was triggered | 2 |
| ctrlKey | Returns whether the "CTRL" key was pressed when the key event was triggered | 2 |
| charCode | Returns the Unicode character code of the key that triggered the onkeypress event | 2 |
| key | Returns the key value of the key represented by the event | 3 |
| keyCode | Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event | 2 |
| location | Returns the location of a key on the keyboard or device | 3 |
| metaKey | Returns whether the "meta" key was pressed when the key event was triggered | 2 |
| shiftKey | Returns whether the "SHIFT" key was pressed when the key event was triggered | 2 |
| which | Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event | 2 |
HashChangeEvent Object
| Property | Description | DOM |
|---|---|---|
| newURL | Returns the URL of the document, after the hash has been changed | |
| oldURL | Returns the URL of the document, before the hash was changed |
PageTransitionEvent Object
| Property | Description | DOM |
|---|---|---|
| persisted | Returns whether the webpage was cached by the browser |
FocusEvent Object
| Property | Description | DOM |
|---|---|---|
| relatedTarget | Returns the element related to the element that triggered the event | 3 |
AnimationEvent Object
| Property | Description | DOM |
|---|---|---|
| animationName | Returns the name of the animation | |
| elapsedTime | Returns the number of seconds an animation has been running |
TransitionEvent Object
| Property | Description | DOM |
|---|---|---|
| propertyName | Returns the name of the CSS property associated with the transition | |
| elapsedTime | Returns the number of seconds a transition has been running |
WheelEvent Object
| Property | Description | DOM |
|---|---|---|
| deltaX | Returns the horizontal scroll amount of a mouse wheel (x-axis) | 3 |
| deltaY | Returns the vertical scroll amount of a mouse wheel (y-axis) | 3 |
| deltaZ | Returns the scroll amount of a mouse wheel for the z-axis | 3 |
| deltaMode | Returns a number that represents the unit of measurements for delta values (pixels, lines or pages) | 3 |
Resource :- w3schools
JavaScript Note
# DOM - document object model
# var oldvlaue = document.getElementById("myID").value; //Getting
# document.getElementById("myId").value = "new value" //Setting
#<p id=“myID"></p>
<script>document.getElementById("myID").innerHTML= “Let’s Learn DOM”;</script>
#<script>
var x = document.getElementById("title");
document.getElementById("myID").innerHTML="The value of element is " + x.innerHTML;
</script>
# element.addEventListener(event, function, useCapture);
# <body>
<button id="myBtn">click</button>
<script>
document.getElementById("myBtn").addEventListener("click", hello);
function hello() {
alert ("Hello World!");
}
</script>
</body>
#element.addEventListener("mouseover", FunctionOne);
element.addEventListener("click", FunctionTwo);
element.addEventListener("click", FunctionThree);
element.addEventListener("mouseout", FunctionFour);
# <body>
<script>
document.write(Date());
</script>
</body>
# <head>
<title>DOM Sample 1</title>
</head>
<body>
Information about this document.<br>
<script type="text/javascript">
document.write("<br>Title: ",document.title);
document.write("<br>Referrer: ",document.referrer);
document.write("<br>Domain: ",document.domain);
document.write("<br>URL: ",document.URL);
</script>
</body>
#DOM Events
#<html>
<head>
<title>DOM Sample</title>
<script type="text/javascript">
function showInfo() {var element = document.getElementById("opener");
var buffer = element.id + " tag is " + element.tagName;
alert(buffer);
element = document.getElementById("actionItem");
buffer = element.id + " tag is " + element.tagName;
buffer += ", type is "+element.type;alert(buffer);}
</script>
</head>
<body>
<p id="opener">The id attribute is very helpful.</p>
<p id="closer">This is the closing paragraph.</p>
<form><button id="actionItem" type="button" onclick="showInfo()">Show Info</button></form>
</body>
</html>
# Creating elements through Nodes
•Steps
1.Create the element (element node)
2.Append it to an existing element
#The HTML Document Object Model is a standard for structuring data on a web page
# javaScript born bcse , some data has to validate at client side
# 3 parts dom- document object model -- node, bom ,ecma script
# DOM - Nodes cn be removed , added , replaced and modifed easily
Developers cn alter the appearance and content of a web page without reloading it
# BOM - browser object model
# Two ways to use the <script> elemnet
#put javascript code directly into page within
tags
#Include javascript from other file
#<script> alert("What you want to print"); </script>
# Including External JS files ,the src attribute is required .
# <script type ="text/javascript" src = "example.js"></script>
#<script> elemnet using src attribute should not include additional javaScript
code between the js code between the <script> and </script> tags . iT is ignored
# <script src = "example.js"></script>
# The main purpose of this <script> format was to keep to external file references,
both css files and javaScript files , in the same area
#Including js in <head> means that all the js code must be downloaded , interpreted
before the page begins rendering
#<script tag in body element>
#Any images and stylesheets that follow the script tag dont start downloading until script
has finished downloading and executing
#A defer external script will start downloading immediately but wont execute until after the
page is rendered.
#DEFERRED SCRIPTS >>>> purpose of defer is to indicate that a script won't be changing
the structure of the page as it executes.
internal file structe not chnged but external may be
#defer atttribute ona a <script> element signals to the browser ,that download should begin
immediately but execution should be deferred.
#even though the <script> elements are included in the documnet <head> they will not be executed
until after the browser has received the closing </html> tag.
# <script type = "text/javascript" defer src = "example.js"></script>
# scripts will be executed in the order in which they appear
<script type = "text/javascript" defer = "defer" src = "example.js"></script>
# the defer , async attribute is supported only for external script files.........
# All old browsers , they will ignore defer , so it is still best to
put deferred scripts at the bottom of the page .
# The async attribute is similar to defer ,in that it changes the way the script is processed.
# async = "async"
# Asynchronous execution - html parsing may continue and script will be
executed as soon as it its ready .
# asnc order is nt guaranteed
# Asynchrous scripts are guaranteed to execute before the page's
load event and may execute before or after DOMContentLoaded
# <script type ="text/javascript" src = "javascript.js" async = "async"></script>
# inline code vs external code >>>internal scripts are great but , it is best to include
javascript using external files is used bcse maintainalbility , caching - if two pages are
using the same file , the file is downloaded only once (this cause to faster page loading)
# js in xhtml file prob fix 1 - not goood way
< greater sign dosent know it
replace all occurences of the less than symbol < with its , html entity (<)
a < b
<script type ="text/javascript">
function compare(a,b)
{
if(a < b)
{
alert("A is less than B");
}
}
</script>
# js in xhtml file fix 2
Wrap the javaScript code in a CDATA section
in XHTML or xml , CDATA sections are used to
indicate ares used to indicate areas of the document
that contain free- from text not intended to be parsed.
<script type ="text/javascript">
<![CDATA[
function compare(a,b)
{
if(a < b)
{
alert("A is less than B");
}
}
]]> </script>
..........this part will be ignore by html parser , but will execute by javaScript
CDATA[
function compare(a,b)
{
if(a < b)
{
alert("A is less than B");
}
}
]
..........
# js in xhtml issues
some browsers complaint to works in xhtml
if browser dont support CDATA sections, CDATA markup must
be offset by javaScript commnets .
That foramt works in all modern browsers
<script type ="text/javascript">
// <![CDATA[
function compare(a,b)
{
if(a < b)
{
alert("A is less than B");
}
}
// ]]>
</script>
#By inculding JavaScript using external files , there's no need to use the xhtml
or comment hacks mentioned previously.
# JavaScript comments
single line comment //
multiline comment /* */
# JavaScript is case sentitive
# typeof is a key word in javaScript , you cnt use it as name of a function.
# identifier = name of a variable , function , property or function argument .
# identifier's name first character must be a letter , _ or $ sign . All other
character may be letters , underscores , dollar signs or numbers.Use camal case .For First
word first leter use simple letter .
eg:- numberOne
# Statements in ECMAScript are terminated by a semicolon .
ommiting the semicolon makes parser determine whether the end of a statement occurs
.It is not recommonded.
Semicolons may improve performance because parsers try to correct syntax errors by inserting
semicolons where they appear to be .
# document.write(samp_str + "<br/>");
document.write("String Variable finally Length is" + stringVar.length + "<br/>");
document.write("String Variable substring " + stringVar.substring(6,12) + "<br/>" );
document.write("SFinal letter" + stringVar.charAt(stringVar.length - 1) + "<br/>");
document.write("Index of T is " + stringVar.indexOf('t') + "<br/>") ;
# String cant be multiplied , if you try to multiply number and string .
then javaScript treated that string as to number
var str_var = "5" ;
var num_var = 6 ;
var total = str_var + num_var ; //56
var multiply = str_var * num_var ; //30
total = Number(str_var) + num_var ; //11
var num_var = String(num_var);
# var folat_var = 3.14156767877 ;
var floar_str = folat_var.toFixed(5); //3.14156
document.write((round_num1 <= round_num2) + "<br/>") ;
# var vehicles = new Array("car","truck","van") ;
document.write( vehicles[1] + "<br/>") ;
# for (i in vehicles)
{
document.write(vehicles[i] + "<br/>") ;
}
# var rand_var = (5 < 10) ? "5 is less than 10 ":"5 is greater than 10 " ;
# if (5> 10)
{
document.write("5 is greater than 10" + "<br/>")
}
else if(5<5)
{
document.write("5 is greater than 5" + "<br/>")
}
else
{
document.write("5 is less than 5" + "<br/>")
}
# var town= "Colombo" ;
switch(town)
{
case "Galle" :document.write("Town is Galle"+ "<br/>") ;break ;
case "Colombo" :document.write("Town is Colombo"+ "<br/>") ;break ;
default :document.write("Town is not defined"+ "<br/>") ;break ;
}
#While loop
var count = 1 ;
while(count <= 10)
{
if(count == 6 )
{
break ; // 2,4 will be print
}
if(count % 2 )
{
document.write(count + "<br/>") ;
count ++ ;
}
document.write(count + "......"+ "<br/>") ;
count ++ ;
}
# //Do while loop
var numThree = 12 ;
do
{
document.write("Inside Do " + numThree + "</br>") ;
numThree -- ;
}
while (numThree > 8 );
# //For LOop
for(var num = 0 ; num < 11 ; num ++)
{
document.write( num + "<br/>");
}
# if your browser dont understand javaScript
<body>
<script language="javascript" type ="text/javascript">
<!---Hide javaScript
function compare(a,b)
{
if(5>10)
{
alert("A is less than B");
}
}
-->
</script>
<noscript>
<h3>This site requires JavaScript</h3>
</noscript>
</body>
# <script type="text/javascript" src="js/addFunction.js"></script>
<!--Adding external javascript file -->
# Function we dont have to again again tasks
//Created In another .js file
function addingTwoNumbers(numOnee , numTwoo)
{
var total = numOnee + numTwoo ;
return total ;
}
# //Calling function from the external javaScript file.....Begin.....
document.write( " Sum of 7 and 9 is ..... = " + addingTwoNumbers(7 , 9 )) ;
//Calling function from the external javaScript file.....End.......
####### Tutorial Part 2 ######
# In header tag
<head >
<style>
#h3style
{
color: gray;
}
</style>
</head>
#<body onResize ="changeImage();" onLoad = "alert('website Loaded');">
<script language = "javascript" type ="text/javascript">
<!-- Hide JavaScript
function changeImage()
{
document.getElementById("idImgSucess").style.height = "35%" ;
document.getElementById("idImgSucess").style.width = "35%" ;
return true ;
}
function alertMe()
{
alertMsg = document.idImgSucess.src + "\nHeight: " + document.idImgSucess.height + "\nWidth: "
+ document.idImgSucess.width ;
alert(alertMsg) ;
return true ;
//Has error of TypeError: document.idImgSucess is undefined
}
function changeColor()
{
document.getElementById("h3style").style.color = "red" ;
document.getElementById("h3style").firstChild.nodeValue = "Excited" ;
return true ;
}
function changeAgain()
{
document.getElementById("h3style").style.color = "gray" ;
document.getElementById("h3style").firstChild.nodeValue = "Bored" ;
return true ;
}
function showParagraph()
{
document.getElementById("idFirstP").style.visiblity = (document.formm.firstPara.checked)? "visible" :"hidden" ;
document.getElementById("idSecondP").style.visiblity = (document.formm.secndPara.checked)?"visible" :"hidden" ;
document.getElementById("idThirdP").style.visiblity = (document.formm.thirdPara.checked)? "visible" :"hidden" ;
return true ;
}
-->
</script>
<noscript>
<h3>This site requires JavaScript</h3>
</noscript>
<img src ="sccess.jpeg" id = "idImgSucess" onClick= "alertMe();" onDblClick="alert('You Double Clicked');" />
<h3 id = "h3style" onMouseOver = "changeColor();" onMouseOut = "changeAgain();">RollOver </h3>
<p id = "idFirstP">This is a Paragraph </p>
<p id = "idSecondP">This is a Paragraph </p>
<p id = "idThirdP">This is a Paragraph </p>
<form name = "formex">
<input type = "checkbox" name = "firstPara" onClick ="showParagraph();"/>
<input type = "checkbox" name = "secndPara" onClick ="showParagraph();"/>
<input type = "checkbox" name = "thirdPara" onClick ="showParagraph();"/>
</form>
<br/>
<br/>
<form name = "formex">
<input type = "checkbox" name = "firstPara" onClick ="showParagraph();"/>
<input type = "checkbox" name = "secndPara" onClick ="showParagraph();"/>
<input type = "checkbox" name = "thirdPara" onClick ="showParagraph();"/>
</form>
<form name = "formTwo">
<p>Text Input </p>
<input type = "text" name = "textInput" onBlur = "alert('onBlur Trigger');" onFocus ="alert('onFocus Triggered');"/>
</form>
</body>
</html>
####w3
# var person = "John Doe", carName = "Volvo", price = 200;
# var x = "5" + 2 + 3;
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
output will be 523
var x = 2 + 3 + "5";
output will be 55
# += x += y x = x + y
%= x %= y x = x % y
/= x /= y x = x / y
# JavaScript Comparison Operators
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
#JavaScript Logical Operators
Operator Description
&& logical and
|| logical or
! logical not
#JavaScript Type Operators
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
#JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001 1
| OR 5 | 1 0101 | 0001 0101 5
~ NOT ~ 5 ~0101 1010 10
^ XOR 5 ^ 1 0101 ^ 0001 0100 4
<< Zero fill left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010
Bitwise operators are fully described in the JS Bitwise chapter.
#Operand Operator Operand
100 + 50
###
JavaScript Operator Precedence Values
Value Operator Description Example
19 ( ) Expression grouping (3 + 4)
18 . Member person.name
18 [] Member person["name"]
17 () Function call myFunction()
17 new Create new Date()
16 ++ Postfix Increment i++
16 -- Postfix Decrement i--
15 ++ Prefix Increment ++i
15 -- Prefix Decrement --i
15 ! Logical not !(x==y)
15 typeof Type typeof x
14 * Multiplication 10 * 5
14 / Division 10 / 5
14 % Modulo division 10 % 5
14 ** Exponentiation 10 ** 2
13 + Addition 10 + 5
13 - Subtraction 10 - 5
12 << Shift left x << 2
12 >> Shift right x >> 2
12 >>> Shift right (unsigned) x >>> 2
11 < Less than x < y
11 <= Less than or equal x <= y
11 > Greater than x > y
11 >= Greater than or equal x >= y
10 == Equal x == y
10 === Strict equal x === y
10 != Unequal x != y
10 !== Strict unequal x !== y
6 && Logical and x && y
5 || Logical or x || y
3 = Assignment x = y
3 += Assignment x += y
3 -= Assignment x -= y
3 *= Assignment x *= y
3 %= Assignment x %= y
3 <<= Assignment x <<= y
3 >>= Assignment x >>= y
3 >>>= Assignment x >>>= y
3 &= Assignment x &= y
3 ^= Assignment x ^= y
3 |= Assignment x |= y
Pale red entries indicates experimental or proposed technology (ECMASScript 2016 or ES7)
Expressions in parentheses are fully computed before the value is used in the rest of the expression.
## JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more:
var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object
#JavaScript has dynamic types. This means that the same variable can be used to hold different data types:
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
# Strings are written with quotes. You can use single or double quotes:
# var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
# Booleans can only have two values: true or false.
var x = true;
var y = false;
#JavaScript arrays are written with square brackets.
var cars = ["Saab", "Volvo", "BMW"];
# JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
# You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
#The typeof operator can return one of these primitive types:
string
number
boolean
null
undefined
# The typeof operator can return one of two complex types:
function
object
Example
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof {name:'John', age:34} // Returns "object"
typeof function myFunc(){} // Returns "function"
The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
# Unfortunately, in JavaScript, the data type of null is an object.
You can empty an object by setting it to null:
var person = null; // Value is null, but type is still an object
#Difference Between Undefined and Null
typeof undefined // undefined
typeof null // object
null === undefined // false
null == undefined // true
#Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};
# <script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
#HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being submitted:
<form action="/action_page_post.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
##
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
#HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
Constraint validation HTML Input Attributes
Constraint validation CSS Pseudo Selectors
Constraint validation DOM Properties and Methods
#Constraint Validation HTML Input Attributes
Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element
#The typeof operator can return one of these primitive types:
string
number
boolean
null
undefined
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
#The typeof operator can return one of two complex types:
function
object
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof {name:'John', age:34} // Returns "object"
typeof function myFunc(){} // Returns "function"
The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
# var person; // Value is undefined, type is undefined
#Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
#In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
#Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};
#Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
#<p id="demo"></p>
<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old.";
</script>
#You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
# objectName.methodName()
#Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword "new", the variable is created as an object:
var x = new String(); // Declares x as a String object
var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.
#In JavaScript, objects and functions are also variables.
In JavaScript, scope is the set of variables, objects, and functions you have access to.
JavaScript has function scope: The scope changes inside functions.
# Local variables are created when a function starts, and deleted when the function is completed.
# A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.
#If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the value is assigned inside a function.
#
Subscribe to:
Posts (Atom)
Some interesting things to explore more
Here some some things to study more , How Google Search works https://developers.google.com/search/docs/fundamental...
-
"Injection attacks": Common Types of Injection Attacks : There are several types of injection attacks, including SQL injection,...
-
With Java 25 , One interesting changes can view is JEP 512, "Compact Source Files and Instance Main Methods," significa...
-
ArrayList in Java ArrayList is a collection API used for storing elements using dynamic array. The dynamic array is an array in w...