If you take a look at this fiddle it will seem fine, but if you click next and move down 2 to 3 times, and then click "memory" (in top nav) it takes .active back to the first .item,
then if you click 'NEXT' again it continues to go to the next element from the prior one we left off of.
I am trying to reset it and continue based on where we go after clicking on the top nav.
Faulty jQuery:* Two click functions both adding active*
var items = $('.item'),
currentItem = items.filter('.active'),
last = items.last();
$("#next-button").on('click', function () {
currentItem.removeClass('active');
var nextItem = currentItem.next();
if (nextItem.length) {
currentItem = nextItem.addClass('active');
if (currentItem.is(last)) {
$('#slide-buttons').addClass('red');
}
}
var items = $('.item');
$(".breadcrumb-cell .breadcrumb").click(function () {
var theID = $(this).data("id");
items.filter(function() {
return $(this).data('category') === theID;
}).addClass('active');
});
});
Fiddle
I Googled "how to reset .next() jquery" but couldn't find anything, not sure if that's even the right thing to do?
The problem you had was that currentItem didn't get updated when you clicked on a breadcrumb.
I made a lot of changes, mostly "streamlining" things. I removed your global variables and based the current item on the active class instead. Check: http://jsfiddle.net/kQabJ/17/
$("#next-button").on('click', function () {
var nextItem = $('.active').removeClass('active').next();
if (!nextItem.length) {
nextItem = $('.item').first();
}
nextItem.addClass('active');
});
$(".breadcrumb-cell .breadcrumb").on('click', function () {
$('.active').removeClass('active');
var theID = $(this).data("id");
$("#" + theID).addClass('active');
});
Note that I also modified your DOM a bit to make it easier to select an item when a user clicks a breadcrumb. That change is using an ID on your .items instead of data. This way you can do $("#" + theID) rather than filtering based on data.
Since these things are uniquely identifying your .item elements themselves - it makes since to use an id anyway, but if this is not what you not you can always change that part back.
You just need to update currentItem, see http://jsfiddle.net/kQabJ/13/
$(".breadcrumb-cell .breadcrumb").on('click', function () {
items.removeClass('active');
var theID = $(this).data("id");
items.filter(function() {
return $(this).data('category') === theID;
}).addClass('active');
currentItem = items.filter('.active');
});
Try this code
You were not updating the currentItem, which was causing the problem.
var items = $('.item'),
currentItem = items.filter('.active'),
last = items.last();
$("#next-button").on('click', function () {
currentItem = items.filter('.active');
var nextItem = currentItem.next();
currentItem.next().length > 0 ? currentItem.next().addClass('active')
: items.first().addClass('active');
currentItem.removeClass('active');
});
$(".breadcrumb-cell .breadcrumb").on('click', function () {
items.removeClass('active');
var theID = $(this).data("id");
items.filter(function () {
return $(this).data('category') === theID;
}).addClass('active');
});
Check Fiddle
Related
I have this Jquery function to click on an element when its ready. its an interval doing it , the following function:
MonitorAndClick(selector) {
var ele = $(selector);
if (ele.length == 0) {
var intervalid = setInterval(function () {
var ele = $(selector);
if (ele.length > 0) {
ele[0].click();
clearInterval(intervalid);
return true;
}
}, 500);
} else {
ele[0].click();
return true;
}
}
the problem is in some cases , its not working. however this is an interval , and it's checking the element to be ready every 0.5 sec, so how can it be possible ? is there any other way to check the element is ready ?
additional note:
I have an accordion. I have a function to open the accordion->open one of the items->open the tab page in detail section
this is the function :
//--reach to this point, open accordion index 2--------
ShowAccordion(2);
//----open the item with specific Id in accordion items------
setTimeout(function () {
var selector = "tr[gacategory = '/myprotection/mywills/item_" + parseInt(willId) + "]";
MonitorAndClick(selector);
}, 500);
the point is this element SHOULD be there , sometimes its not loading fast enough , and I WANT TO HAVE A WAY TO CHECK IF ITS LOADED, THEN CLICK ON THAT.
Updated code after comments
var selector = "tr[gacategory = '/myprotection/mywills/item_" + parseInt(willId) + "]";
$("#selector").ready(function () {
console.log('**********.... selector is loaded ....*****');
if (!$("#selector").hasClass('selected'))
MonitorAndClick(selector);
});
still not working.
Why do you want to rely on 0.5 seconds delay to make sure your element is present in DOM. You should be invoking this function only after your element is present in the DOM. If there is another condition that drives when this element is added to the DOM, then call this function once that condition is achieved.
You may want to try https://api.jquery.com/ready/
It seems like jquery ready function can be applied on individual elements too
I was successful in getting the id of all images within a div when clicking the div with the following codes below:
<script type="text/javascript">
function getimgid(){
var elems = [].slice.call( document.getElementById("card") );
elems.forEach( function( elem ){
elem.onclick = function(){
var arr = [], imgs = [].slice.call( elem.getElementsByTagName("img") );
if(imgs.length){
imgs.forEach( function( img ){
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
});
}
</script>
The codes above works perfectly, doing an alert message of the image id when clicking card div. Now what I want is to run this function without clicking the div in every 5 seconds. I have tried setInterval (getimgid, 5000), but it doesn't work. Which part of the codes above should I modify to call the function without clicking the div. Any help would be much appreciated.
JSFiddle
You should be calling it this way:
setInterval (function(){
getimgid();
},5000);
also remove binding of click event for element.
Working Fiddle
Use elem.click() to trigger click
function getimgid() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick = function () {
var arr = [],
imgs = [].slice.call(elem.getElementsByTagName("img"));
if (imgs.length) {
imgs.forEach(function (img) {
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
elem.click();
});
}
setInterval(getimgid, 1000);
DEMO
Problem: You are not triggering the click in setInterval. You are only re-running the event binding every 5 secs.
Solution: Set Interval on another function which triggers the click. Or remove the click binding altogether if you don't want to manually click at all.
Updated fiddle: http://jsfiddle.net/abhitalks/3Dx4w/5/
JS:
var t;
function trigger() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick();
});
}
t = setInterval(trigger, 5000);
I have a function that writes out to a cooke the value of the DIV that holds that data that I want to show, the cookie code works, the toggle code works but when the page refreshses, I can get the list of repeater elements, itterate through them, determine if the section should be hidden or not but I can't use visible, I can't use .show() or .hide(), I know this has to be easy but what am I over looking???
This is my working code for the slidetoggle that works and writes the true or false to the cooke based on the repeater title attribute:
$(document).ready(function () {
$("a.toggle").click(function () {
var inObj = $(this).parent().find('div#fader');
var inTitle = inObj.attr('title');
inObj.slideToggle('fast', function () {
docCookies.setItem(inTitle, inObj.is(':visible').toString());
});
});
});
This is the code block that I have the problem with, specifically, the .show() and the .hide() are not known methods, so I have the object in inObj[] collection, I am not sure how to cast this or deal with this in javascript.....
$(window).load(function () {
var inObj = $('div#fader');
for (var i = 0; i < inObj.length; i++) {
var objTitle = inObj[i].title;
var item = docCookies.getItem(objTitle);
if (item == "true") {
inObj[i].show();
}
else {
inObj[i].hide();
}
}
});
Use $(inObj[i]).show() and $(inObj[i]).hide().
Not sure how to formulate this but here it goes.
I am checking if a var exists (content), if it doesnt i set it.
Problem is next click, it still behaves as if there is no var content. But why??
Here my code:
$("#nav a").click(function(event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
if (!content)
{
var content = $('<div>').load(load);
$(".content").append(content);
}
else
{
var position = content.offset();
$(document).scrollTop(position);
}
});
It never results to else, so always a click is made the whole load and append function repeats.
Basically how can I record that content for this particular link has been loaded once, so the else function should be performed next time?
Also, what is wrong with my if(!content) statement? Is it because of scope?
In Javascript functions determine the scope of an object. You need to place content in the global scope. Currently it is created within the anonymous function assigned to the click event handler, so when the function is executed again content is out of scope causing it to return false.
var content;
$("#nav a").click(function(event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
if (!content)
{
content = $('<div>').load(load);
$(".content").append(content);
}
else
{
var position = content.offset();
$(document).scrollTop(position);
}
});
Try to make the var content as a global variable rather than a local one, like you are doing right now. That's why the if (!content) result as true always, like:
var content;
$("#nav a").click(function (event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
if (!content) {
content = $('<div>').load(load);
$(".content").append(content);
} else {
$(document).scrollTop(content.offset());
}
});
Just to show what happens, when value of content is not set at first and then set again:
var content;
console.log(content); // undefined
console.log(!content); // true
content = 'text';
console.log(content); // text
console.log(!content); // false
Thanks to everyone for answering the first question about the checking if var exists.
I ended up ditching this whole concept it turned out the
one()
function is what I needed all along. In order to only execute a function once and another function on all following clicks.
Here it is:
$(document).ready(function() {
//Ajaxify Navi
$("#nav a").one("click", function(event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
var content = $('<div>').load(load);
$(".content").append(content);
$(this).click(function(event) {
event.preventDefault();
var position = content.offset().top;
$(document).scrollTop(position);
$("body").append(position);
});
});
});
What this is is the following:
1st click on a button loads content via ajax and appends it, second click on the same button only scrolls to said content.
I have a modal box in jQuery which I have created to display some embed code. I want the script to take the id of the link that is clicked but I can't seem to get this working.
Does anyone know how I can do that or why this may be happening?
My jQuery code is:
function generateCode() {
var answerid = $('.openembed').attr('id');
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<code><iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '" frameborder="0"></iframe></code>');
}
$(document).ready(function () {
$('.openembed').click(function () {
generateCode();
var answerid = $('.openembed').attr('id');
$('#box').show();
return false;
});
$('#embed').click(function (e) {
e.stopPropagation()
});
$(document).click(function () {
$('#box').hide()
});
});
My mark-up is:
Embed
Embed
Your problem is here:
$('.openembed')
returns an array of matched elements. Your should instead select only the clicked element.
$('.openembed') works correctly if you assing a click event to all elements that have this class. But on the other hand, you're unable do know which is clicked.
But fortunately in the body of handler function click you could call $(this).
$(this) will return the current (and clicked element).
// var answerid = $('.openembed').attr('id'); // Wrong
var answerid = $(this).attr('id'); // Correct
// Now you can call generateCode
generateCode(answerid);
Another error is the body of generateCode function. Here you should pass the id of selected element. This is the correct implementation.
function generateCode(answerid) {
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '"frameborder="0"></iframe>');
}
Here I have implemented your code with the correct behavior: http://jsfiddle.net/pSZZF/2/
Instead of referencing the class, which will grab all members of that class, you need to reference $(this) so you can get that unique link when it is clicked.
var answerid = $(this).prop('id');
$('.openembed').click(function () {
generateCode();
var answerid = $(this).attr('id');
$('#box').show();
return false;
});
Use $(this). $('.openembed') refers to multiple links.
var answerid = $('.openembed').attr('id');
needs to be
var answerid = $(this).prop('id');
The other answers are trying to fix the click() function, but your issue is actually with the generateCode function.
You need to pass the clicked element to the generateCode function:
$('.openembed').click(function () {
generateCode(this);
And modify generateCode:
function generateCode(element) {
var answerid = element.id;
Of course var answerid = $('.openembed').attr('id'); within the click code isn't correct either, but it doesn't seem to do anything anyway.
Get the id when the correct anchor is clicked and pass it into your generateCode function
$('.openembed').click(function () {
var answerid = $(this).attr('id');
generateCode(answerid)
$('#box').show();
return false;
});
Change your function
function generateCode(answerid) {
// dont need this line anymore
// var answerid = $('.openembed').attr('id');