jQuery function works on click() not on ready() - javascript

I'm trying to change the 'href' attribute to match that of a sibling element.
$(function() {
$(".container").click(function() {
var href = $(this).find('.one').attr('href');w
$(this).find('.two').attr('href', href);
});
})
when the 'click();' event handler is used and I click on .container, the href of .two updates, however, when just using ready(); to execute it as soon as the page loads, it doesn't execute.

If you want to keep the context within .container element, just change click function to each, like this:
$(function() {
$(".container").each(function() {
var href = $(this).find('.one').attr('href');
$(this).find('.two').attr('href', href);
});
});
For more information about jQuery's each function, please refer here.
UPDATE
Also you can improve the performance a bit by caching the value of $(this), like this:
$(function() {
$(".container").each(function() {
var $this = $(this),
href = $this.find('.one').attr('href');
$this.find('.two').attr('href', href);
});
});
UPDATE 2
If you don't care about the context of .container, here is the code that will change href attributes of all those elements with class .two, which come after an element with class .one.
Here is the live example in JSFiddle.

Related

Run function on active anchor

I'm new to jQuery and want to highlight div's if the div's anchor id is set.
I currently have this construct which only works on page load with an valid anchor attached.
$(document).ready(function(){
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
});
This works only on page load with a set anchor. How can I make this more dynamic so the script executes whenever the anchor changes?
jQuery can hook into the hashchange event so you can do this:
$(window).on('hashchange', function(e){
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
});
You can make it a function and call it with every update.
function updateAnchors() {
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
}
Then call updateAnchors() when more anchors are loaded.

Can't get cloned element to keep originals events

I'm trying to clone an element that is passed into a function and all events associated to it, as there are $('.example').on('click', function(e) ... )} events like this defined in document ready.
So I do following:
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
and I try to clone this element along side its events here (I need to grab parent as .html() returns only inner html, hence element itself) :
function surpriseMe(element) {
var newElement = element.parent().clone(true,true).html();
surprise.insertBefore(element.parent());
if (numElements == 3) {
newMonth = $('<li class="item-dragable-placeholder">'+ newElement +'</li>
}
}
I believe true, true inside .clone() should force parent also grab its children events, but whenever I click on newly placed element, nothing happens
To use event delegation...
Change:
$('.example').on('click', function(e) { ...
To:
$(document).on('click', '.example', function(e) { ...
Note: Instead of using document, find the closest ancestor element (container) that's available on page load and use that.
when you do your insert, instead of inserting the new element, you ask to insert only the html, remove the html part, it will give you the element and its functionalities.
var newElement = element.parent().clone(true,true).html();
See the following (example)[http://jsfiddle.net/dshun/1j9khfnc/4/](please note, since the example code given is not complete. For example, the variable surprise, numElements are not declared. I made some assumptions in my fiddle)
$(document).ready(function(){
var numElements=0;
function surpriseMe(element) {
var newElement = element.parent().clone(true,true);
newElement.insertBefore( ".inner" );
numElements++;
if (numElements == 3) {
newMonth = $('li.item-dragable-placeholder').insert(newElement);
}
}
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
});

Disable CSS link for 1 second after it has been clicked

I'm trying to have a CSS link disabled for 1 second after it has been clicked.
I have tried this without success;
In the header:
<script type="text/javascript">
$(function() {
$("#link").click(function() {
$("#link").attr("disabled", "disabled");
setTimeout(function() {
$("#link").removeAttr("disabled");
}, 2000);
});
});
</script>
Html:
the link text
CSS:
.link:diabled {
some values here.. }
You have a class="link", but with $("#link") you are addressing the id called link.
So write $(".link") everywhere instead of $("#link").
By the way: with .link:disabled you won't address the link as this only works on inputs and buttons. If you need to address it, use .link[disabled="disabled"] { ... } or even better add a class to it called disabled_link and then do in CSS .disabled_link { ... }.
There are quite a few problems here:
You are using # (the ID selector), but your html is using classes.
<a> does not have a disabled attribute
If it did, you would probably want to use .prop instead of .attr
If you change code to use classes, $(".link").prop("disabled", true) would affect all anchors, so you should probably use this.
Because disabled does not exist for <a>, the :disabled selector does not seem to work for CSS.
A working solution would be something like this:
$(".link").click(function() {
var $this = $(this);
$this.addClass('disabled');
setTimeout(function() {
$this.removeClass('disabled');
}, 2000);
});
$(document).on('click', '.disabled', function (e) {
e.preventDefault();
});
http://jsfiddle.net/ExplosionPIlls/PaYcc/
'link' is a class and you are using it as ID. Do $('.link') instead of $('#link').
I think this approach works better. The other allows you to click the link multiple times and mess up the setTimeout this unbinds the event and then re-attaches the event after the setTimeout ex: double click the link
$(".link").click(linkBind);
function linkBind(){
var $this = $(this);
$this.addClass('disabled');
$this.unbind('click');
setTimeout(function() {
$this.removeClass('disabled');
$this.bind('click', linkBind);
}, 2000);
}
$(document).on('click', '.disabled', function (e) {
e.preventDefault();
});
http://jsfiddle.net/PaYcc/1/

jquery get href value and use it as a variable

So I have set up a scrolling code for my website.
<section class="fpage">
<a class="next" href="#view">test</a>
</section>
<section class="cpage">test</section>
In jquery I've got.
$(document).ready(function () {
$('.next').click(function (event) {
var cpage = $(this).find('a').attr('href');
var fpage = $(this).closest('section');
event.preventDefault();
fpage.addClass('anim').delay(500).queue(function(next){
$(this).removeClass().addClass('cpage');
next();
cpage.removeClass('.cpage').addClass('fpage');
});
});
});
I want the var:cpage to take the .next href value (in this case: #view) and use it as the name of it's variable. What have I dont wrong in this instance? And how can I turn the cpage var into #view?
.next is the a itself. you don't need to use .find
var cpage = $(this).attr('href');
OR
var cpage = this.href;
Edit : as cpage is an ID you need to do this to select the element
$(cpage).removeClass('.cpage').addClass('fpage');
As far as I understood, this should solve:
fpage.addClass('anim').delay(500).queue(function(next){
$(this).removeClass().addClass('cpage');
next();
$(cpage).removeClass('.cpage').addClass('fpage');
});
You have a few things out of place but all in all, no biggie.
First,
$('.next').click(function (event) {
var cpage = $(this).find('a').attr('href');
It can't call its self. .next is a class for the a tag, so how can a tag find inner elements with the a tag if it is the only a tag element? jQuery's .find works to find children and grandchildren and such of the element it's called upon. thus this line is just as easy written as:
var cpage = $(this).attr('href');
Second,
cpage.removeClass('.cpage').addClass('fpage');
cpage is only a string variable, not a jQuery object, thus it needs a slight change. Try:
$(cPage).removeClass
I don't know what version of jQuery you are using, but I gave your code a complete scrub down and edit and posted a jsFiddle using the latest jQuery's. Important to note, if you're using an older version, some things might be different, such as .on being .bind or .live in older versions.
jsFiddle
$(function() {
$(".next").on("click", function(e) {
e.preventDefault();
var cPage = $(this).attr("href"),
fPage = $(this).closest("section");
fPage.addClass("anim").delay(500).queue(function(n) {
$(this).removeClass().addClass('cpage');
n();
$(cPage).removeClass('.cpage').addClass('fpage');
});
});
})

Is there an easier way to reference the source element for an event?

I'm new to the whole JavaScript and jQuery coding but I'm currently doing this is my HTML:
<a id="tog_table0"
href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a>
And then I have some slightly ponderous code to tweak the element:
function toggle_table(button_id, table_id) {
// Find the elements we need
var table = $(table_id);
var button = $(button_id);
// Toggle the table
table.slideToggle("slow", function () {
if ($(this).is(":hidden"))
{
button.text("show");
} else {
button.text("hide");
}
});
}
I'm mainly wondering if there is a neater way to reference the source element rather than having to pass two IDs down to my function?
Use 'this' inside the event. Typically in jQuery this refers to the element that invoked the handler.
Also try and avoid inline script event handlers in tags. it is better to hook those events up in document ready.
NB The code below assumes the element invoking the handler (the link) is inside the table so it can traverse to it using closest. This may not be the case and you may need to use one of the other traversing options depending on your markup.
$(function(){
$('#tog_table0').click( toggle_table )
});
function toggle_table() {
//this refers to the element clicked
var $el = $(this);
// get the table - assuming the element is inside the table
var $table = $el.closest('table');
// Toggle the table
$table.slideToggle("slow", function () {
$el.is(":hidden") ? $el.text("show") : $el.text("hide");
}
}
You can do this:
show
and change your javascript to this:
$('a.tableHider').click(function() {
var table = $(this.name); // this refers to the link which was clicked
var button = $(this);
table.slideToggle("slow", function() {
if ($(this).is(':hidden')) { // this refers to the element being animated
button.html('show');
}
else {
button.html('hide');
}
});
return false;
});
edit: changed script to use the name attribute and added a return false to the click handler.
I'm sure this doesn't answer your question, but there's a nifty plugin for expanding table rows, might be useful to check it out:
http://www.jankoatwarpspeed.com/post/2009/07/20/Expand-table-rows-with-jQuery-jExpand-plugin.aspx

Categories

Resources