Jquery Duplication in mobile vs. of table - javascript

I am making a mobile version of my tables, I'm using the following script to help do so:
<script>
$(document).ajaxSuccess(function () {
$('table#CustomerMainTable td').each(function () {
var idx = $(this).index();
$(this).prepend($('table#CustomerMainTable tr th').eq(idx).text());
$('table#CustomerMainTable th').hide();
});
});
</script>
This works fine in my fiddle : http://jsfiddle.net/2EJy3/1/
But in my app, it creates duplicates eg. The td would have the th printed twice, instead of once. Does anyone know what would be causing this?

Since it works in your fiddle, that implies a couple of things: 1) Your document structure is different in your app, or 2) your ajaxSuccess handler is being called twice. Turn on your debugger, or add some logging in your script before your each() call and see if the handler is being invoked twice.

Related

jQuery get attribute of clicked element when content is dynamically generated

I am working on a site where a lot of content is generated dynamically using AngularJS. I need to get the attribute of an element that is dynamically generated using jQuery, but I am having trouble doing so. I have already figured out that I need to use the .on method to click rather than .click. My issue is finding the equivalent of $(this) within the .on method.
Here is my code:
$(document.body).on('click', 'a.card-topic-link' ,function(e) {
e.preventDefault(); // Prevent default action - this works
console.log('The click works!'); // This fires and works just fine
var cardTopicLink = $(this).attr('data-topic-link'); // This is where the problem lies
console.log(cardTopicLink); // This is undefined
}); // End on click
As I stated before, this does not work as the .click does not work for dynamic content:
$('a.card-topic-link').click(function(e) {
e.preventDefault(); // Prevent default action
var cardTopicLink = $(this).attr('data-topic-link');
console.log(cardTopicLink);
});
I feel like there is a simple solution to this problem that I am having trouble finding. The key to this issue is that this is dealing with dynamic content.
Let me know if you have any ideas.
use e.currentTarget, instead of var cardTopicLink = $(this).attr('data-topic-link');, try var cardTopicLink = angular.element(e.currentTarget).attr('data-topic-link');
$(document).ready(function () {
$(document.body).on('click', 'a.card-topic-link' ,function(e) {
e.preventDefault(); // Prevent default action - this works
console.log('The click works!'); // This fires and works just fine
var cardTopicLink = $(e.currentTarget).attr('data-topic-link'); // This is where the problem lies
console.log(cardTopicLink);
}); // End on click
});
plunker with similar code, firing on async loaded content - http://plnkr.co/edit/02rqCrbBVwXiIYff8ktC?p=preview
It turns out that AngularJS was stripping out the attribute data-topic-link as it was parsed. This was happening because the HTML that contained the data-topic-link was passed as a part of the response that Angular was printing in an ng-repeat.
I updated the code so that the HTML with this attribute did not need to be served by AngularJS.

JavaScript alert callback not working inside a function

I am trying to make a image preview containing of about 5-6 images which will appear one after another when user hovers over it (not like a carousel with prev and next buttons). Here is the fiddle consisting of what I gathered so far.. i don't know if this approach is right or not.. but I am stuck as the alert callback is not working. Could someone please tell me what is wrong?
$(function()
{
var imageCount = $('#product_grid_list').find('figure')[0].getElementsByTagName('img');
for (var i = 0, n = imageCount.length; i < n; i++) {
imageCount[i].on('click', function(e)
{
alert('Everything is going fine!');
}
);
}
}
);
The root cause of click event callback can't be triggered is that you're trying to register a event handler on a "DOM" (in this case: imageCount[i]) element in jQuery way. Try to register the event handler like this if you want to use pure javascript solution:
imageCount[i].addEventListener('click', function(e){
alert('Everything is going fine!');
});
Here is a jsfiddle demo.
Note: I didn't consider the cross browser issue in this case.
BTW, try to cache the length of imageCount node list, it will improve the performance.
You are using js AND jQuery at same time. It's wrong. If you use jQuery, than click event will be like this:
$(document).('click', '#product_grid_list figure img', function(){
alert('Everything is going fine!');
});
You are using a mix of jQuery and standalone javascript. You might as well go all the way to jQuery, with something like:
$('#product_grid_list figure:first img').click(function(e) {
alert('Everything is going fine, hopefully!');
});
You did not send the corresponding HTML, so we cannot test whether the above is correct.
it's just a simple click event in jQuery, no need to use js: http://jsfiddle.net/wP3QQ/11/
$('#product_grid_list').find('figure img').click(function(e){
alert('Everything is going fine!');
e.preventDefault();
});
You want the hover effect, so click event should not be used over here. It should be mouseover.
Working Fiddle
Code Snippet:
$(document).on('mouseover','#product_grid_list figure img',function(e){
alert("now it is working");
});
You are attempting to call on(), a jQuery method, on an HTMLElement (a DOM element). You can't do that, jQuery methods can only be called on jQuery collections. It's easy to get a jQuery collection for the elements you desire:
Use .find() to match the images
There's no need for a for() loop, jQuery's .on() will handle looping for you.
You may also want to prevent the default behaviour of your anchors
$(function () {
var imageCount = $('#product_grid_list').find('figure img');
imageCount.on('click', function (e) {
e.preventDefault()
alert('Everything is going fine!');
})
});
JSFiddle

jQuery function calling twice, once from our own js and next from jquery.min.js

Hi, I am using jQuery in my application and for swiping event I used jquery mobile, due to usage of both in one application I had an issue that is the swiping event gets fired twice, one time from my own js file and second time the code copied into jquery.min.js, and executing from there.
$(document).ready(function(){
var wrap = $('.slides_wrap');
var slides = wrap.find('.img_slide');
slides.on('swipeleft', function(e) {
console.log('called swipeleft');
$('a.carousel-control .rightArrow').click();
});
slides.on('swiperight', function(e) {
console.log('called swiperight');
$('a.carousel-control .leftArrow').click();
});
});
Try:
slides.parent().off("swiperight").on(...).click();
or:
slides.parent().off("click").on(...).click();
I think you have bind multiple events in closest elements. If this not work, try with .children() too.

Javascript two clicks - need one

I'm total beginner in JavaScript. The problem is that the code works only when I click on the text two times. I need same, but with one click. The code is on the link:
http://jsbin.com/uTizoKe/1/edit?html,output
I'd really appreciate any help. Thank in advance
Move your script tag to the end of the body of the HTML, and remove the onclick handler from the table tag. This works (here's the jsbin):
<script>
document.getElementsByTagName('table')[0].onclick = setTDOnclickEvents();
function setTDOnclickEvents() {
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
}
</script>
Another option (rather than calling your function based on a table click) is to simply do this:
<script>
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
</script>
Another option is (if you want to use the script in the head of the document), put everything as a function inside of window.onload.
Additionally, it generally a good practice to try to avoid relying on putting event handlers inside HTML elements themselves, and rather handle all that stuff inside your JavaScript.
Remove the onclick from the table and add it as onload to the body
DEMO
Alternatively, you can use window.onload instead of putting it directly in the body
DEMO
The problem is that you have an onclick attached to the table which calls setTDOnclickEvents. So, only when the user clicks the table will that onclick occur.
What you really want is to bind your elements within the table when the page loads. Using jQuery you could do...
$(function() {
setTDOnclickEvents();
});
Replace
<body>
by
<body onload="setTDOnclickEvents()">
There are other ways to do that, like you could just write :
document.onload = setTDOnclickEvents;
Inside your JavaScript
You need to bind your function to an event for it to be fired at all, if it's inside head.
I'd expect your code not to work at all, strange that it does. Perhaps some default behavior somewhere, not worth investigating...
PS: I just saw that you're biding the click event for table to the function, so that would explain the strange behavior. Yeah, remove that.
The problem is that you're calling setTDOnclickEvents() on click of the table element. So you're not attaching the click events until after you've clicked the first time.
Instead, you can move this into the body onload attribute.
There are some other improvements you could make to this code to, to make it simpler and more up-to-date. If interested, please let me know, I'd be happy to help.

jQuery click() not working on replaced html

I am trying to create a go-moku game using jquery,php, and mysql database.
I have a ajax function that updates the a board every second if needed.
var turnCount = -1;
setInterval(function(){
$.get('includes/boardControl.php',{turn: turnCount }, function(data){
if(data != "")
{ $("#board").html(data);
turnCount = $("#turnCount").text();
$("#turnCount").text("")
}
});
}, 1000);
This works just fine, it checks the database to see if turn has been incremented and replaces the board if it has. Now what I want to ultimately do is create a click function that use Ajax to update the board and turn count in the database. I am hoping to somehow use the N'th selector do determine what square I'm clicking on.
I have several questions.
1) My click function right now is
$(document).ready(function() {
$("td > img").click(function(){
alert("clicked");
});
});
as of right now it works on a extra test table I wrote into the html, but not on the table created with the previous function. What am I doing wrong?
2) The tutorials I've looked at so far dictate that I should write code in the following way.
$(document).ready(function() {
//code here
});
When i asked a question last night, I was told that I was over complicating things with my functions. So when should i use a document.ready function and when not? And is it fine to put all of my scripts into one document.ready function or should I have multiple?
3)
Once I get the click image to work I am hoping to send a X,Y coordinate to the server and change that corresponding spot on the board. How would I determine what cell in the table is clicked in order to know what coordinates to use? (or is there a much easier way?)
sounds like you need to change
$("td > img").click(function(){
alert("clicked");
});
to
$("td > img").live('click',function(){
alert("clicked");
});
Edit: For jQuery 1.9 and later you can do:
$("#board").on('click', 'td > img', function(){
// handle click
});
The $(document).ready() function only fires when the page first loads - in order to make this work try something like this:
function bindClicks() {
$("td > img").click(function(){
alert("clicked");
});
}
$(document).ready(bindClicks);
This will allow you to call bindClicks() later on if need be to bind the click events of a new table.
1) Are you re-wiring the click event after the ajax content loads?
The $(document).ready function will fire as soon as the page is fully loaded, but won't fire after ajax calls. So you will need to re-wire the click event after every ajax call:
2) KISS. Keep it as simple as possible. If you have 50+ lines inside a document.ready statement you might want to create some functions.
3) The best way to accomplish this might be to assign a specific ID to each cell and capture that in the click event. You can then pass that to the server and update the specific cell on the return.
Are you sure JQuery is matching you query:
$("td > img")
I would load firefox with firebug and check that your actually getting match first. The second table your creating may have a slightly different structure then you expected and firebug can show you the exact structure also.
Goodluck.

Categories

Resources