jQuery .each() over .wp-caption - javascript

WordPress add an extra 10px to the .wp-caption container when a caption in present. I'm trying to use jQuery to remove the extra 10px. I've been able to do this thanks to the answers in this question, but I realized that b/c there are sometimes multiple images in a post, I need to use something to the effect of .each() to iterate. The code below works for the first image but then wrongly applies the first image's with to the container of the second image. How can I correct the .each() to work properly?
jQuery().ready(function() {
jQuery(".wp-caption").each(function(n) {
var width = jQuery(".wp-caption img").width();
jQuery(".wp-caption").width(width);
});
});
Example w/ javascript on
Example w/ javascript off
Update: The most streamlined solution from below:
jQuery().ready(function( $ ) {
$(".wp-caption").width(function() {
return $('img', this).width();
});
});
Or substituting $ with jQuery to prevent conflicts:
jQuery().ready(function( jQuery ) {
jQuery(".wp-caption").width(function() {
return jQuery('img', this).width();
});
});
Both work! =)

this is a reference to the current element in the .each().
jQuery().ready(function( $ ) {
$(".wp-caption").each(function(n) {
var width = $(this).find("img").width();
$(this).width(width);
});
});
...so from this, you use the find()[docs] method to get the descendant <img>, and its width().
You could also pass a function directly to width(), and it will iterate for you.
jQuery().ready(function( $ ) {
$(".wp-caption").width(function(i,val) {
return $(this).find("img").width();
});
});
...here, the return value of the function will be the width set to the current .wp-caption.
EDIT: Updated to use the common $ reference inside the .ready() handler.

Related

Simple Mobile jQuery Switch button & alternative to .toggle latest jQuery

I'm working on a simple jQuery switch button. The kind you mostly see on mobile.
[ on | off ]
I have the below snippet that I found in a jsfiddle. But it won't work; I tried wrapping it in -
$('.slider-button').toggle(function(){
$(this).addClass('on').html('Quizz');
},function(){
$(this).removeClass('on').html('Read');
});
})
I tried wrapping it in a on ready as well.
$(document).ready(function(){
$('.slider-button').toggle(function(){
$(this).addClass('on').html('Quizz');
},function(){
$(this).removeClass('on').html('Read');
});
})
I'm loading the latest in jQuery:
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
Mark-Up:
<div class="slider-frame">
<span class="slider-button">OFF</span>
</div>
It simply wont toggle onClick.
Edit: Here's an attempt at a fiddle; http://jsfiddle.net/Hn27Q/
Still can't get it; and actually none of the CSS3 is being seen at mobile; any suggestions appreciated.
Bill
The .toggle version that accepted functions to alternate on clicks has been removed as of v1.9 (see http://api.jquery.com/toggle-event/)
You can see What to use instead of `toggle(...)` in jQuery > 1.8? for an implementation of that functionality as an extension..
You should use it like this
$('.slider-button').toggleClick (function(){
$(this).addClass('on').html('Quizz');
},function(){
$(this).removeClass('on').html('Read');
});
});
for ease of use i copy the code here
$.fn.toggleClick = function(){
var methods = arguments, // store the passed arguments for future reference
count = methods.length; // cache the number of methods
//use return this to maintain jQuery chainability
return this.each(function(i, item){
// for each element you bind to
var index = 0; // create a local counter for that element
$(item).click(function(){ // bind a click handler to that element
return methods[index++ % count].apply(this,arguments); // that when called will apply the 'index'th method to that element
// the index % count means that we constrain our iterator between 0 and (count-1)
});
});
};

document.getElementById() alternative in jQuery

UPDATE: I'm sorry that my thread was misinterpreted by many users. I'll try to be more clear.
I'm using Drupal and I have created three floating banners. On the frontpage there is a block (block1) that displays one floating banner and after refresh the second one is appearing and for the third too.
Like a wrote before these banners has a little X button to stop overflow.
I've putted this script in a one of the banners and it's working great.
<script language="javascript">
function doexpand() {
document.getElementById("block1").style.overflow = "visible";
}
function dolittle() {
document.getElementById("block1").style.overflow = "hidden";
}
</script>
The real problem is that in categories pages I have #block2 and in articles #block3.
These block are displaying the same banners. The code over is working only for a one ID. In this case #block1. document.getElementById is not working for more ID's as I read from other topics.
I've tried with jQuery with two blocks idents like this:
(function ($) {
function doexpand() {
$("#block1,#block2").css("overflow","visible");
}
function dolittle() {
$("#block1,#block2").css("overflow","hidden");
}
})(jQuery);
It's not working.
The firebug/console displays: ReferenceError: doexpand is not defined.
I've tried with a single block too with jQuery like this:
(function ($) {
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
})(jQuery);
and it's displaying the same error.
Note: Drupal has a different wrapping and it's like this:
(function ($) {
//your existing code
})(jQuery);
Please have a look on jQuery Selectors.
I think in your case, it is better to apply style with help of css for multiple elements. e.g. :
<script language="javascript">
function doexpand() {
$('.block').style.overflow="visible";
}
function dolittle() {
$('.block').style.overflow="hidden" ;
}
</script>
Please add class="block" to all of blocks for which you want to apply this style/function, it will apply on all of the blocks having css class "block".
jQuery?
HTML:
<div class="block2"></div>
JS:
function doExpand(selector) {
if ( $(selector).length ) {
$(selector).css({'overflow':'visible'});
}
}
Calling with non ID selector would look like this: (jQuery syntax):
doExpand('.block2');
The above code is perfectly valid in jQuery (which is a JavaScript library).
If you want to use a more typical jQuery code, you can do
$('#block1').css('overflow', 'visible');
You can expend it to multiple id like this :
$('#block1, #block2').css('overflow', 'visible');
You always can get the DOM object from a jQuery object, which means you could also have adapted your code to use jQuery selectors using
$('#block1').get(0).style.overflow="visible";
(this specific example isn't smart : no need to use jQuery if you don't use a complex selector or jQuery functions)
Pretty simple really, jQuery selection is based on css selectors for the most part. These selectors are then translated into an array of dom objects held in a jQuery object.
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
You should never have more than one HTML element with the same ID (Which is why document.getElementById only returns one element)
You can just refeerence block2, block3 directly document.getElementById("block2").style.overflow="hidden" ;
Or use getElementByClassName
var elements = document.getElementsByClassName("yourClass")
Which will pick up all elements with a specific class.
If you want to use jQuery like the other answers are suggesting you can match on the element name. For example:
$('div[id^="block"]').css("overflow", "visible");
This will match all div element where their ID starts with block. You can also use other wildcards such as * for contains and $ for ends with.
Here is your Javascript Code in jQuery. I dont understand what you want do do, but you could pass the params in the function. Example under this code.
<script language="javascript">
function doexpand() {
$("#block1").css({'overflow': 'visible'});
}
function dolittle() {
$("#block1").css({'overflow': 'hidden'});
}
</script>
Here is it
<script language="javascript">
function doexpand(element) {
$("#" + element).css({'overflow': 'visible'});
}
function dolittle(element) {
$("#" + element).css({'overflow': 'hidden'});
}
</script>
Than you could call it like: doexpand("theIDofTheElement");
Alternative to document.getElementById("an_element);
in Jquery is: $("#an_element");
It will work fine in JQuery, it's just that JQuery makes things faster and less verbose.

How to get Information about an element without a callback

I have different container that get reloaded on different events. I have plenty of them, so I gave each container the class load.
This is how all of them look like:
<div class="load" data-href="facebook">
</div>
I also have a function, that is triggered by various actions:
function get_timing(time)
{
$(".load").load("myfolder/mod_"+$(this).attr("data-href")+".php?action="+time, function() {
alert('Here I could use this:' + $(this).attr("data-href"));
}
}
I know that I cannot use this in the example above, I could only use it in the callback. My question is: How can I use attributes of the object to define the path of the load function.
This is how it could work:
function get_timing(time)
{
$(".load").fadeIn(10, function()
{
$(this).load("myfolder/mod_"+$(this).attr("data-href")+".php?action="+time, function() {
alert('loaded');
}
}
}
Is there a way to do this without the asynchronus function (in this case .fadIn) around)
Hope I could explain my problem - thank you in advance!
If you want to go along with classes you can reference them via an index:
var element = $(".load").get(0);
console.log($(element).attr("data-href"));
Note that you have to re-jQueryfy element via $(element) in order to access attr()
If you want to read out all elements with a given class I recommend $.each()
//$.each($(".load"), function(index, value){
$(".load").each(function(index, value){
console.log( $(value).attr("data-href"));
});
Try to give your container an id:
<div class="load" data-href="facebook" id="facebookcontainer">
</div>
Then instead of using this, you can use $("#facebookcontainer") in your javascript.

Changing image source with Jquery

Using Jquery, I've managed to make a dropdown login form triggered by clicking a button. However, I am also trying to change the direction of the arrow next to it by replacing the src image, and it appears to do nothing.
$("#login_panel").slideToggle(200).toggle(
function() { $("#arrow").attr('src', '/src/east.gif';) },
function() { $("#arrow").attr('src', '/src/south.gif';) }
);
This can be seen at:
http://dev.mcmodcenter.net (The 'Login' button)
$(document).ready(function() {
$("#login_panel").slideToggle(200).toggle(
function() { $("#arrow").attr('src', '/src/east.gif';) },
function() { $("#arrow").attr('src', '/src/south.gif';) }
);
for (var i = 0; i < 2; i++) {
$(".mod").clone().insertAfter(".mod");
}
$(".mod").lazyload({
effect: "fadeIn"
});
});
You can directly access this.src - no need to create a new jQuery object for that:
$('#arrow').toggle(
function() { this.src = '/src/south.gif'; },
function() { this.src = '/src/east.gif'; }
);
And if you prefer to do it via .attr() at least use $(this) (DRY - don't repeat yourself - in this case, don't specify the selector more often than necessary)
$("#arrow").toggle(
function(){$("#arrow").attr("src", "/src/south.gif");},
function(){$("#arrow").attr("src", "/src/east.gif");}
);
You left off the "#" in the handler functions. By just referring to "arrow", you were telling jQuery to look for (presumably absent) <arrow> tags.
Now, as to the larger situation, what you're setting up there is something that'll make the image change when the image itself is clicked. Your description of your goal makes me think that that's not quite what you want, but it's hard to tell. If you want some other element to control the changes to the image, then you'd attach the handler(s) elsewhere.
Is the image you want to change that little black arrow next to the login button? If so, then what should happen is that the code to set the image should be added to the existing handler that slides the login form up and down. (By the way, in Chrome the login box shows up in what seems like an odd place, far to the left of the button.)
looks like you forget to put the # before the arrow in $("arrow")
it should be like this
$("#arrow").toggle(
function(){$("#arrow").attr("src", "/src/south.gif");},
function(){$("#arrow").attr("src", "/src/east.gif");}
);
$("arrow") will match <arrow>, you lost the #
Also, the toggle method does not take two functions as its arguments, it works in a completely different way to what you are trying to do with it. Yes, it does, there are two different toggle methods for jQuery (insert rant about awful API design)
And now you have completely edited the code…
Your code now immediately assigns strings to the this.src (where this is (I think) the document object), and then passes those two strings as arguments to the toggle method (which are not acceptable arguments for it)
And now you have completely edited it again…
This code should work:
$('#login_button').click(function() {
$(this).find('#arrow').attr('src', function(i, v) {
return v.indexOf('east.gif') < 0 ? '/src/east.gif' : '/src/south.gif';
});
$('#login_panel').slideToggle(200);
});

Select tags within a string using jQuery

I have my website getting a value as a result of an ajax call. After that, I would like to insert that result (a string) into a tag. However, I would like to insert that result in a way that (1) it must have opacity = 0, then (2) it will slideDown() so the whole content list being pushed down using animation, and finally (3) change opacity = 1. Imagine this is just like a Facebook message list insert process
The way I am planning to do this is to return the result string from ajax to opacity=0 first. However, I don't know how to use jQuery to select a tag from within a string. I know jQuery only select from the DOM. So how to do this? Any advice?
Thanks
I'd consider putting the return value inside a SPAN. Hide the container that will hold it. Set the opacity of the SPAN to 0, then add the result to it and put it in the container. Once that is done, slide the container down and animate showing the result in the callback to the slideDown method.
$.ajax({
...
success: function(data) {
var container = $('#container').hide();
$('<span />').css( 'opacity', 0 )
.html(data.result)
.appendTo(container);
container.slideDown('normal', function() {
$(this).( 'span:first' )
.animate( { 'opacity': 1.0 } );
});
}
...
});
Hide() is a jquery function, meaning that only works on a jquery object, so you have to first inject the html in the DOM, and then call hide() on the DOM element.
$('#msgList').load (url,data,function(html){
var $this = $(this); // cache $(this) for performance
$this.hide().html(html); // inject the html in the DOM
$('#aa', $this).hide(); // hide #aa
$this.show(); // reveal the messageList
});
The following will make the ajax call using the simple .get() wrapper.
Then the callback function will load the response into a jquery object and find the tag you want.
It then hides this tag and appends it to a div container.
Finally it will slide it down.
//do ajax call
$.get( url, function(html) {
//load html into a jQuery object, find the tag by id then hide it
var $el = $(html).filter('#someId').hide();
//append element to the dom and slide it down
$el.appendTo('#someDiv').slideDown('slow');
});

Categories

Resources