Apply to function to multiple elements - javascript

HTML:
<div class="container-fluid">
<div class="sidebar">
<ul class="pills">
<li id="l1"><a id="link1">Lesson 1</a></li> <hr>
<li id="l2"><a href="#" >Lesson 2</a></li> <hr>
<li id="l3"><a href="#" >Lesson 3</a></li> <hr>
</ul>
<div class="span16" id="target">
</div>
Javascript:
$('#l1').click(function(){
$('#target').fadeOut('fast', function(){
$('#target').load("lesson/lesson1.html", function(){
$('#target').fadeIn('slow');
});
});
});
I have 5 links within my webpage, I was wondering if there was anyway to make this one piece of code instead of copy + pasting it multiple times.

$('a.AjaxLink').click(function(){
var url = this.href;
$('#target').fadeOut('fast')
.load(url, function(){ $(this).stop(true, false).fadeIn('slow'); });
});
return false;
});
This code handles the click event for all <a>s with a class of AjaxLink.
In the click handler, it grabs the href, fades out your #target, and performs the AJAX load.
When the AJAX load finishes, it stops the animation (in case the AJAX was faster than the fade), then fades it back in.
Finally, it tells the browser not to take the default action (navigating to the page) by returning false.

Use class instead of id. Select elements using class.
Also you can use .each() method

You could do this with a new jQuery method. Given this HTML:
<a class="hello" href="#">Hello</a>
<a class="goodbye" href="#">Goodbye</a>
<div id="target"></div>
You'd use this code:
jQuery.fn.switchTarget = function( target, href ) {
var $target = $(target);
this.bind( 'click', function(e) {
e.preventDefault();
$target.fadeOut('fast', function() {
$target.load( href, function() {
$target.fadeIn('slow');
});
});
});
return this;
};
$('.hello').switchTarget( '#target', 'hello.html' );
$('.goodbye').switchTarget( '#target', 'goodbye.html' );

Related

jquery mobile listview - touchstart event to fire on <li> element

When I try and fire an event on a listview <li> item it seems that the whole element is not considered, but only the elements inside it:
<ul data-role='listview' data-filter='true' data-filter-placeholder='Search Your Trucks..' data-inset='true' data-mini='true'>
<li id=tg_1><a id=tg_2 href=#divdet>ONE</a> TEST </li>
<li id=tg_2><a id=tg_2 href=#divdet>TWO</a> FOO </li>
</ul>
The function handling touchstart (which handles touchstart of multiple elements):
document.addEventListener('touchstart', function (e) {
switch(e.target.id) {
case ...
..other elements...
break;
default:
if(e.target.id.substr(0,3) == "tg_")
$.ajax({
... do request ....
})
$("#divdet").html(from_ajax_data);
}
}
}
The issue is that it is working, but only when clicking on specific parts of the <li> element. I'd like it to work every time a <li> is clicked.
The concept is that with the href i can move to the next page of the app using effect such as slide, whilst with the touch event I load data into the div.
You can move to the next page with transition using script as well:
http://api.jquerymobile.com/pagecontainer/#method-change
<ul data-role='listview' data-filter='true' data-filter-placeholder='Search Your Trucks..' data-inset='true' data-mini='true'>
<li id="tg_1"><a id="tg_1a" href="#">ONE</a> TEST </li>
<li id="tg_2"><a id="tg_2a" href="#">TWO</a> FOO </li>
</ul>
$(document).on("click", "li", function(e){
var id = $(this).prop("id");
if(id && id.substr(0,3) == "tg_") {
var from_ajax_data = "from ajax html"; //ajax call here
$("#divdet").html(from_ajax_data);
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#divdet", { transition: "slide" } );
}
});
Working DEMO

Why can't I target li element with jQuery.click()?

I have this html:
<ul id="ul_places_list">
<li data-placesCode="6">
<a class="places_dtl" href="#">
<div>
<img src="http://dev.mysite.it/images/9_1418893365.jpg">
</div>
<label>Coming Out</label>
</a>
</li>
<li data-placesCode="8">
<a class="places_dtl" href="#">
<div>
<img src="http://dev.mysite.it/images/9_1418893594.jpg">
</div>
<label>Friends</label>
</a>
</li>
</ul>
and this javascript
$(document).delegate('a','click',function(){//used to switch page
console.log('delegate executed');
var a = $(this);
if(a.attr('href') != '#'){
event.preventDefault();
toPage(a.attr('href'));
}
});
$(document).ready(function(){
$('#ul_places_list li').click(function(){
var code = $(this).attr('data-placesCode');
console.log('code is: ' +code);
});
});
The problem is that when I click on list element only the delegated click on the element fires and not the event on the "li" element.
The "li" elements are added after an Ajax call.
What's going? What am I missing?
This )}; was the problem. Should be this });.
$(document).delegate('a','click',function(){//used to switch page
console.log('delegate executed');
var a = $(this);
if(a.attr('href') != '#'){
event.preventDefault();
toPage(a.attr('href'));
}
});
$(document).ready(function(){
$('#ul_places_list li').click(function(){
var code = $(this).attr('data-placesCode');
console.log('code is: ' +code);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul id="ul_places_list">
<li data-placesCode="6">
<a class="places_dtl" href="#">
<div>
<img src="http://dev.mysite.it/images/9_1418893365.jpg">
</div>
<label>Coming Out</label>
</a>
</li>
<li data-placesCode="8">
<a class="places_dtl" href="#">
<div>
<img src="http://dev.mysite.it/images/9_1418893594.jpg">
</div>
<label>Friends</label>
</a>
</li>
</ul>
The below answer actually is just a different implementation of your code.
The real answer is
This )}; was the problem. Should be this });.
From the other answer: https://stackoverflow.com/a/27571915/561731
But you really should be using .on in new code :-)
Old answer:
Try using .on
So you can do:
$(document).on('click', 'a', function () {
//event for anchor tag
});
$(function () {
$('#ul_places_list').on('click', 'li', function () {
//stuff for li click event
});
});
if you add the "li" elements in a AJAX call you should add the click event after the elements load. Add this when ajax call end:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(addEventToControls)
function addEventToControls()
{
$('#ul_places_list li').click(function(){
var code = $(this).attr('data-placesCode');
console.log('code is: ' +code);
});
}
The add_endRequest Manager fire the handler when a Ajax Call end.

JS are crashing after jquery load function

I tried to load my content with the jQuery load function into index.html's content area. I succeeded with that, but my Javascript isn't working. I want to call it on each click of my menu's elements. Is it possible?
click here to see the page
menu:
<div id="nav" class="section group">
<div id="menu" class="col span_9_of_12">
<ul id="navmenu">
<li>Hakkımda</li>
<li>Portfolyo</li>
<li>İletişim</li>
<li>Fotoğraflar</li>
</ul>
</div>
load function:
$(document).ready(function() {
$('#content').load($('#navmenu li a:last').attr('href'));
var hash = window.location.hash.substr(1);
var href = $('#navmenu li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('#navmenu li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('slow',loadContent);
$('#load').remove();
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('slow',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('slow');
}
return false;
});
});
UPDATE: My original answer no longer applies. OP changed the page implementation and question completely since I answered.
But as I stated in a comment below, The easytabs documentation states that the tab element and the panel divs must all be inside the container div.
<div id="tab-container" class="tab-container">
<ul class='etabs'>
<li class='tab'>Hakkımda</li>
<li class='tab'>Portfolyo</li>
<li class='tab'>Fotoğraflar</li>
<li class='tab'>İletişim</li>
</ul>
<div id="hakkimda">
...
</div>
<div id="portfolyo">
...
</div>
<div id="iletisim">
...
</div>
<div id="fotograflar">
...
</div>
</div>
Rather than adding script inline, do this
$( "#jqc_content" ).load( "content/aboutme.html", function() {
carouselfn(); // call your carousel invocation function here
});
From documentation
Callback Function
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed
I fixed it finally. It's all about the html structure.

Listview click event only happens first time with dialog in jQuery Mobile?

I am attaching a click event on the listview items, which feeds into a dialog. When I close the dialog and try to click on another item, the click event doesn't happen again. Is there anything wrong with what I have or a better way?
var chapterId;
$(document).on('click', '.listview', function (e) {
var source = $(e.target).closest('li');
var id = source.attr('data-chapter');
if (id) chapterId = id;
else chapterId = null;
});
$(document).on('pageinit', '#mydialog', function (e) {
if (chapterId) {
//DO SOMETHING WITH ID LIKE GET FROM DATABASE
}
});
This is what my listview looks like:
<ul data-role="listview" data-inset="true" class="listview">
<li data-chapter="1"><a href="dialog.html" data-rel="dialog">
<h2>Chapter 1</h2>
<p>Some text</p>
</a></li>
<li data-chapter="2"><a href="dialog.html" data-rel="dialog">
<h2>Chapter 2</h2>
<p>Some text</p>
</a></li>
<li data-chapter="3"><a href="dialog.html" data-rel="dialog">
<h2>Chapter 3</h2>
<p>Some text</p>
</a></li>
</ul>
The first click works and passes the correct Id in the dialog pageinit event, but closing the dialog and clicking another doesn't fire the click (I also tried vclick but same results). Any help would be greatly appreciated!
dont use global variables of data-transfer between pages. Use data property of the DOM elements. Consider I have a listview like this :
<ul data-role="listview" id="songlist" data-theme="c" data-divider-theme="a" data-inset="true">
<li data-role="list-divider" role="heading">Song List</li>
<li data-chapter="1">Sweet Child 'O Mine</li>
<li data-chapter="2">Summer of '69</li>
<li data-chapter="3">Smoke in the Water</li>
<li data-chapter="4">Enter Sandman</li>
<li data-chapter="5">I thought I've seen everythin</li>
I have this in a page with id #mypage1. The pageinit function of that page will contain your click function. Changes :
Dont bind the click to the ul. Bind it to the a tag.
Use e.preventDefault() to stop the re-direction to happen before u get the chapter Id
Store the chapter Id in data of #dialogPage
use changePage to redirect.
Here's the code :
$(document).on("pageinit", "#mypage", function () {
$(this).on("click", "#songlist a", function (e) {
//prevent dialog transition
e.preventDefault();
//get the data-chapter
var source = $(this).closest("li").attr("data-chapter");
//set that in #dialogPage's data for later use
$("#dialogPage").data("chapter", source);
//redirect to dialog
$.mobile.changePage(this.href, {
role: "dialog"
});
});
});
For the dialog box, I have a markup like this :
<div data-role="page" id="dialogPage">
<div data-role="header">
<h2>Dialog</h2>
</div>
<div data-role="content">
<p></p>
</div>
</div>
For dialog, changes made :
Dont use pageinit. that event happens only once, use pageshow or pagebeforeshow, which will happen everytime you reach the dialog.
get the value of the chapterid from data of #dialogPage :
var chapterId= $(this).data("chapter");
Here's the code :
//dont use pageinit, use pageshow or pagebefore show for dialog
$(document).on("pagebeforeshow", "#dialogPage", function () {
//get the chapter Id from data
var chapterId= $(this).data("chapter");
//do anything you want with it.
$(this).find('[data-role="content"] p').html("<b>Chapter ID : </b>" +));
});
And the demo : http://jsfiddle.net/ZmV5D/3/

Making click work only on parent item

I have footer with some content inside. ANd i made my footer show\hide on click. But now if i click on any item inside footer(i have navbar there) my footer reacting on show\hide aswell. How do i make only parent(footer) to react on clicks, and none of child elements? I'm using jquery mobile.
Here is my code:
<div data-role="footer" data-id="main_footer" data-position="fixed" data-fullscreen="true" data-visible-on-page-show="false" data-tap-toggle="false" >
<div data-role="navbar" data-iconpos="top">
<ul>
<li><a id="menu-item-home" data-icon="custom" href="index.html" class="ui-btn-active ui-state-persist"> </a></li>
<li><a id="menu-item-near-me" data-icon="custom" href="near-me.html"> </a></li>
<li><a id="menu-item-rewards" data-icon="custom" href="rewards.html"> </a></li>
<li><a id="menu-item-invite" data-icon="custom" href="invite.html"> </a></li>
<li><a id="menu-item-profile" data-icon="custom" href="profile.html"> </a></li>
</ul>
</div><!-- /navbar -->
</div>
<!-- /footer -->
</div>
And JS
$("#index").live('pagecreate', function() {
$("[data-role='footer']").live("click", function() {
if ($("[data-role='footer']").hasClass('ui-fixed-hidden'))
{
$("[data-role='footer']").removeClass('ui-fixed-hidden');
}
else
{
$("[data-role='footer']").addClass('ui-fixed-hidden');
}
});
});
TLDR;
I want to make links inside my footer to work, but not trigger footer to show\hide while click on link
You could add
$(document).on("click", "[data-role='footer'] li", function(e) {
e.stopPropagation();
});
Note that I used on instead of live, which is deprecated. Note also that jQuery has a useful toggleClass function. So I'd suggest you replace your existing code with
$("#index").live('pagecreate', function() {
$(document).on("click", "[data-role='footer'] li", function(e) {
e.stopPropagation();
});
$(document).on("click", "[data-role='footer']", function() {
$("[data-role='footer']").toggleClass('ui-fixed-hidden');
});
});
For a variety of reasons, you shouldn't actually use .live, but replace it with .on. Anyway, I think this will work:
... 'click', function (e) {
if ($(e.target).not("[data-role=footer]")) {
e.stopPropagation();
}
});
this should work...i suggest u to use on instead on live...
$(document).on("click", "[data-role='footer']", function(e) {
if(e.target != this){
return;
}
if ($("[data-role='footer']").hasClass('ui-fixed-hidden'))
{
$("[data-role='footer']").removeClass('ui-fixed-hidden');
}
else
{
$("[data-role='footer']").addClass('ui-fixed-hidden');
}
});
So your problem is that , the link in the footer not works. The easiest solution for this, is bind a click event to the link inside your footer and use either $.mobile.changePage() or window.location() method to open the desired url. Add this to your code :
$("[data-role=footer] a").bind("click",function(){
$.mobile.changePage($(this).attr("href"));
});

Categories