/    Sign up×
Community /Pin to ProfileBookmark

Javascript/jQuery On Load Issue

I have the following function that runs when the page is loaded, but I want it to only run when a button is clicked. How would I go about doing that?

[CODE]
<script>
$(document).ready(function () {
$.fancybox({
‘width’: ‘80%’,
‘height’: ‘80%’,
‘autoScale’: false,
‘transitionIn’: ‘fade’,
‘transitionOut’: ‘fade’,
‘type’: ‘iframe’,
‘scrolling’ : ‘no’,
‘href’: ‘cmetogo-offer.html’
});
});
</script>
[/CODE]

And this is the anchor tag that I would want to trigger it:

[code=html]<a href=”index.html”>Login Here</a>[/code]

Any suggestions?

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@iBeZiDec 20.2012 — First put the code you want to run in it's own function, give the anchor tag an id, then add an event listener to detect when the link is clicked and point it at the function

[CODE]
<script>
function fancybox(e) {

$.fancybox({
'width': '80%',
'height': '80%',
'autoScale': false,
'transitionIn': 'fade',
'transitionOut': 'fade',
'type': 'iframe',
'scrolling' : 'no',
'href': 'cmetogo-offer.html'
});
e.preventDefault();
}
$(document).ready(function () {
$('#link').click(fancybox);
});

</script>

[/CODE]


[code=html]
<a href="index.html" id="link">Login Here</a>
[/code]
Copy linkTweet thisAlerts:
@NtrimgsauthorDec 20.2012 — I'm just curious why you put the "e" in between the function parentheses...?
Copy linkTweet thisAlerts:
@iBeZiDec 20.2012 — It's an event handler function so the function passes through an event object with information and functions related to the event which is stored in e, you use that to prevent the default action of clicking the link, which would be to go to the anchor or another page.
Copy linkTweet thisAlerts:
@ZachLiuDec 20.2012 — I think it is better to change your HTML element from a link to a button. I think some browsers may check your <a> link underground so the event maybe automatically triggers. There may be some other issues, but I am not sure.
Copy linkTweet thisAlerts:
@iBeZiDec 20.2012 — Semantically, a button would make more sense, but using a link shouldn't cause any issues if you prevent the default action.
×

Success!

Help @Ntrimgs spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...