I am trying to complete some action when a link is clicked in my application.
For example, I am creating a manual that has multiple internal links within the document. Currently, I would be handling them like so:
function waitForClick()
{
$('#about').click(function()
{
$('#container').slideDown();
});
$('#using').click(function()
{
changeContent...
});
<!-- etc, etc -->
}
Is there a better way to handle multiple click events, so that I don't need an event for every single item. I'm sure there has to be a way to delegate which item was clicked.
HTML:
<li><a id="about" href="#">About this Application</a></li>
<li><a id="using" href="#">Using this Manual</a></li>
<li><a id="pages" href="#">Pages:</a></li>
<!-- etc, etc -->
This is supposed to be a table of contents for the manual. So there are going to be a lot of local links.
Personally I'd use something like the below. It avoids a ton of events being cast individually and is scalable enough for your purpose. All you do is add a class of "clickEventClasss" (or whatever takes your fancy) to each element that should have an event an add an id so you can recognise each one.
function waitForClick()
{
$('.clickEventClass').click(function() {
var id = $(this).attr('id');
switch(id) {
case 'about':
//Logic
break;
case 'using':
//Logic
break;
}
});
}
You could bind click events to classes rather than ID's.
<a class="navigationLink" href="home.com">Home</a>
<a class="navigationLink" href="about.com">About</a>
<a class="navigationLink" href="contactus.com">Contact Us</a>
$(".navigationLink").click(function() {
//Do something cool
});
You could use a class where you assign the click event to.
After this the following is possible:
$(".class").click(function()
{
if($(this).attr("id") == "about")
{
//code here
}
else if($(this).attr("id") == "using")
{
//code here
}
}
Related
I am building a hybrid application out of Jquery Mobile, Cordova and WordPress. My current question is regarding my navigation between "pages" in index.html that have the data-role="page" attribute.
Current Setup: I am using data-role="navbar" inside data-role="header" and EACH page has the following header:
<div data-role="navbar">
<ul>
<li><a class="blue-button home-button" href="#" data-transition="slidefade">HOME</a></li>
<li><a class="blue-button artist-refresh artist-button" href="#" data-transition="slidefade">ARTIST</a></li>
<li><a class="blue-button show-button" href="#" data-transition="slidefade">SHOW INFO</a></li>
</ul>
</div><!-- /navbar -->
main.js file I am trying to add event listeners to each of the navigation elements by class name and .ui-page-active class I am also bundling in a few other unique elements that have clickEvents but I reference them by ID:
function setupMainNav() {
console.log("Settign Up SUB NAV");
$('.ui-page-active .show-button').on('click', function () {
console.log("In the show info click");
$.mobile.changePage("#show-info", {
transition: "slide"
});
});
$('.ui-page-active .home-button').on('click', function () {
console.log("In the show info click");
$.mobile.changePage("#home", {
transition: "slide"
});
});
$('#artistContactButton').on('click', function () {
console.log("Show Contact Form");
$.mobile.changePage("#artist-contactpage", {
transition: "slide"
});
});
$('div.ui-page-active a.artist-button').on('click', function () {
console.log("artist button click");
$.mobile.changePage("#cyan-home", {
transition: "slide"
});
});
$('#show_link').on('click', function () {
$.mobile.changePage("#cyan-home", {
transition: "slide"
});
});
$('#shop_link').on('click', function () {
$.mobile.changePage("#shop-home", {
transition: "slide"
});
});
}
What I do is try to all the setupMainNav() function every-time a page changes using the .on('pagecreate') but only the first page that is loaded which has the #show_link and #shop_link elements with those ID's and of course those are the only two.
What are best practices for setting up navigation that is controlled via the JS and not the <a href>
Disclaimer: these are a few of what I think of as "best practices." Others may disagree; YMMV. Also this is assuming you don't want to use libraries or frameworks like Vue.js or React.js, which in general will do things quite differently. Depending on circumstances these libraries can have both advantages and drawbacks.
But within those limits, the general idea is this:
Keep the event handler generic, so that one function can do multiple things.
Pass in stuff that differs between links as attributes. This keeps things related to the activity together at the link.
I like to attach the event listener higher up in the DOM and then handle the events as they bubble. In this case we're attaching the event to the ul tag, and catching any click events that bubble up from a tags. IMHO this has a few advantages:
if you mutate the list, new links will automatically use the current event handler.
you only have one event handler attached to the DOM, instead of 3 (however many a tags you have)
this also gives you the chance to add other event listeners directly to specific a tags if you want to do something special before (or instead of) the default action. Because events attached directly happen first, and then the event bubbles. If you want it to happen instead of, you would just call e.stopPropagation() to prevent the event from bubbling.
Also what I've done sometimes in the past is to have a single generic page with header and navbar, and then load the main content div via ajax. This has the very visually pleasing effect that when you go to a different page the navbar stays put, and doesn't reload. You could easily do this in the example code below, if changePage was doing an XHR/fetch, and then loading the contents into a main content div.
In this greatly simplified example, I show how we can use the href, innerText, and a data attribute to do different things depending on which link is clicked. Of course you can do as much (or as little) as you want/need in this regard.
$('ul.navbar').on('click', 'a', function(e) {
var t = e.target;
var info = t.dataset.info || '';
console.log("click " + t.innerText + ' ' + info);
$.mobile.changePage(t.href, {
transition: "slide"
});
e.preventDefault();
return false;
});
// stub of $.mobile.changePage
$.mobile = {
changePage: function(href, opts) {
console.log('changePage', href);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='navbar'>
<li>HOME</li>
<li>ARTIST</li>
<li>SHOW INFO</li>
</ul>
I am building a hybrid application out of Jquery Mobile, Cordova and WordPress. My current question is regarding my navigation between "pages" in index.html that have the data-role="page" attribute.
Current Setup: I am using data-role="navbar" inside data-role="header" and EACH page has the following header:
<div data-role="navbar">
<ul>
<li><a class="blue-button home-button" href="#" data-transition="slidefade">HOME</a></li>
<li><a class="blue-button artist-refresh artist-button" href="#" data-transition="slidefade">ARTIST</a></li>
<li><a class="blue-button show-button" href="#" data-transition="slidefade">SHOW INFO</a></li>
</ul>
</div><!-- /navbar -->
main.js file I am trying to add event listeners to each of the navigation elements by class name and .ui-page-active class I am also bundling in a few other unique elements that have clickEvents but I reference them by ID:
function setupMainNav() {
console.log("Settign Up SUB NAV");
$('.ui-page-active .show-button').on('click', function () {
console.log("In the show info click");
$.mobile.changePage("#show-info", {
transition: "slide"
});
});
$('.ui-page-active .home-button').on('click', function () {
console.log("In the show info click");
$.mobile.changePage("#home", {
transition: "slide"
});
});
$('#artistContactButton').on('click', function () {
console.log("Show Contact Form");
$.mobile.changePage("#artist-contactpage", {
transition: "slide"
});
});
$('div.ui-page-active a.artist-button').on('click', function () {
console.log("artist button click");
$.mobile.changePage("#cyan-home", {
transition: "slide"
});
});
$('#show_link').on('click', function () {
$.mobile.changePage("#cyan-home", {
transition: "slide"
});
});
$('#shop_link').on('click', function () {
$.mobile.changePage("#shop-home", {
transition: "slide"
});
});
}
What I do is try to all the setupMainNav() function every-time a page changes using the .on('pagecreate') but only the first page that is loaded which has the #show_link and #shop_link elements with those ID's and of course those are the only two.
What are best practices for setting up navigation that is controlled via the JS and not the <a href>
Disclaimer: these are a few of what I think of as "best practices." Others may disagree; YMMV. Also this is assuming you don't want to use libraries or frameworks like Vue.js or React.js, which in general will do things quite differently. Depending on circumstances these libraries can have both advantages and drawbacks.
But within those limits, the general idea is this:
Keep the event handler generic, so that one function can do multiple things.
Pass in stuff that differs between links as attributes. This keeps things related to the activity together at the link.
I like to attach the event listener higher up in the DOM and then handle the events as they bubble. In this case we're attaching the event to the ul tag, and catching any click events that bubble up from a tags. IMHO this has a few advantages:
if you mutate the list, new links will automatically use the current event handler.
you only have one event handler attached to the DOM, instead of 3 (however many a tags you have)
this also gives you the chance to add other event listeners directly to specific a tags if you want to do something special before (or instead of) the default action. Because events attached directly happen first, and then the event bubbles. If you want it to happen instead of, you would just call e.stopPropagation() to prevent the event from bubbling.
Also what I've done sometimes in the past is to have a single generic page with header and navbar, and then load the main content div via ajax. This has the very visually pleasing effect that when you go to a different page the navbar stays put, and doesn't reload. You could easily do this in the example code below, if changePage was doing an XHR/fetch, and then loading the contents into a main content div.
In this greatly simplified example, I show how we can use the href, innerText, and a data attribute to do different things depending on which link is clicked. Of course you can do as much (or as little) as you want/need in this regard.
$('ul.navbar').on('click', 'a', function(e) {
var t = e.target;
var info = t.dataset.info || '';
console.log("click " + t.innerText + ' ' + info);
$.mobile.changePage(t.href, {
transition: "slide"
});
e.preventDefault();
return false;
});
// stub of $.mobile.changePage
$.mobile = {
changePage: function(href, opts) {
console.log('changePage', href);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='navbar'>
<li>HOME</li>
<li>ARTIST</li>
<li>SHOW INFO</li>
</ul>
Im trying to create a false hover event for my site using jQuery...
I have created the following only all the child elements in my list now return false also as opposed to linking to the correct page...
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
$("ul.sf-menu li.i").click(function(e) {
e.preventDefault();
});
}
Has anybody an idea on an alternative method that could work?
HTML
<ul class="sf-menu"> <li>Home<li class="i">Weddings
<ul>
<li>Peel Suite</li>
<li>The Hall</li>
<li>The Grounds</li>
<li>Food & Drink</li>
<li>Pricing</li>
</ul>
</li>
well. without HTML its kind of hard to tell. But you are stopping the default behavior of the browser when the user clicks on the li (and therefor also its children, which I suppose is an anchor/link).
you could check if its a link or an anchor on click and handle it differently;
$("ul.sf-menu li.i").click(function(e) {
if (e.target.nodeName!=="A"){
e.preventDefault();
//do your hover code
}
else{
//do nothing, because the user wants the link to load
}
});
change youre selector so it only matches the first level of listpoints, also i dont see a class i so you might need to drop that from the selector aswell.
$("ul.sf-menu > li")
I have multiple list items in an unordered list. Each list item looks like this:
<li class="something" onclick="function(somePHPparameter)">somePHPparameter</li>
The function will populate a div that's currently empty via ajax, if that matters. I want it so that by default, when the page first finishes loading, clicking on the li will populate the div. If the same li is clicked again, then it will empty the div. If another li was clicked instead, just change the contents with a different "somePHPparameter". My current implementation is like this:
$('.continent').click(function(){
if ($(this).hasClass('select')){
$("#box").empty();
$('.continent').removeClass('select');
}
else{
$('.continent').removeClass('select');
$(this).addClass('select');
}
});
One, is there any faulty logic with my code? Anything extra? Two, the actual issue is that even though the class is removed, the onclick that populates the div still occurs.
e.preventDefault() and e.stopPropagation() don't work. Any ideas?
event.preventDefault() and event.stopPropagation() will not help in this case because two different functions are already called when click is triggered. One function is called inline and the other is called using jQuery.
To avoid this, remove onclick attribute from <li> and call that function inside jquery click handler.
If it's PHP generated param, add it as a rel attribute to <li> and use in jquery handler like below:
<li class="something" rel="somePHPparameter">somePHPparameter</li>
--
$('.continent').click(function(){
if ($(this).hasClass('select')){
$("#box").empty();
$('.continent').removeClass('select');
}
else{
$('.continent').removeClass('select');
$(this).addClass('select');
var PHPparam = $(this).attr('rel');
functionCallUsing(PHPparam);
}
return false;
});
Just a rough idea.
You can simply do
$('.continent').click(function(){
if ($(this).hasClass('select')){
$("#box").empty();
$('.continent').removeClass('select');
}
else{
$('.continent').removeClass('select');
$(this).addClass('select');
}
return false;
});
what my current Code do :
i have this HTML
<li>
<span>Logged in as</span>
<a class="user" href="#"><?php echo $this->loggedas ?></a>
<a id="loginarrow" href="javascript: void(0);"></a>
</li>
this is my JS for above loginarrow id
$("#loginarrow").click(function() {
$("#logindrop").toggle("slow");
return false;
});
its working great but i can close it by clicking it again.
i dont want so i want that if its open and i click on background so it must close.
for that i did so
$("#loginarrow,body").click(function() {
$("#logindrop").toggle("slow");
return false;
});
now its working cool,But Got another problem.
1 = i have many other html elements in Page (Body) in which there are other events to call.so in this case whenever i click other elements in my page so its Toggling my this div loginarrow.
i want the same functionality but not on my other elements only on background.
Any Hint
close it only when it visible.
$("body").click(function() {
if ($("#logindrop").is(":visible"))
$("#logindrop").hide("slow");
});
A fundamental design principle for good browser performance is to only capture events while you're interested in them.
So put your .click() handler on the #loginarrow element, but in that handler register a one-off event handler on the body that will close it again. Something like (untested):
$('#loginarrow').click(function() {
$('#logindrop').show('slow');
$('body').one('click', function() {
$('#logindrop').hide('slow');
});
return false;
});
This will ensure that you're not unnecessarily intercepting every click on the body except when you really need to.
​See http://jsfiddle.net/alnitak/vPHaj/