jQuery width() not working - javascript

I'm trying to get the width of the first div of the specific class "span4" on my Bootstrap site, but the script simply fails to execute the second line where I call width(). Here's what I have:
var span = $('div.span4').first();
spanWidth = span.width();
The strange part of this is that I have similar working code immediately after that works fine when I remove the above two lines and set spanWidth to a constant:
elements = $('a.backlink');
elements.each(function() {
var a = $(this);
if (a.width() > spanWidth) {
var aText = a.text();
var lastIndex = aText.lastIndexOf(' ');
var aTruncated = aText.substring(0, lastIndex);
a.text(aTruncated + '...');
}
});
Any idea what might be causing this? I've tried a lot of different ways to format those two lines differently, such as switching to an each() method, condensing to one line, and using [0] and get(0) instead of first().

Try to set the span's display to inline-block.

#SimonM's comment led me to try replacing my implied global spanWidth with an explicit global window.spanWidth, and now everything works. Thank you!

Related

Using CSS classes as jQuery variables

To my understanding, in jQuery you can set a variable then use it later down the line.
var x = 2;
function add() {
x = x + 2;
}
In my code, I have a CSS class as a variable.
var scroll = $('.verticalScrollBar');
function changeScrollBar() {
...
TweenMax.set(scroll, {css:{height:scrollBarHeight+'%'}});
...
}
However, this does not seem to work. Initially, I thought it might have been a problem with GSAP TweenMax so I tried the following code.
function changeScrollBar() {
...
TweenMax.set($('.verticalScrollBar'), {css:{height:scrollBarHeight+'%'}});
...
}
To my surprise this did work. So my question is why does the line of code TweenMax.set($('.verticalScrollBar'), {css:{height:scrollBarHeight+'%'}}); work but this line of code TweenMax.set(scroll, {css:{height:scrollBarHeight+'%'}}); does not?
Working example JSFiddle
Broken example JSFiddle
Changing:
var scroll = $('.verticalScrollBar');
To:
var scroll = '.verticalScrollBar';
Results in your broken example operating as expected.
.....
Edited (twice now) for an explanation as to why this is happening.
As #Katana314 pointed out, the var scroll bit is defining a jQuery object that doesn't exist at this point. $(".verticalScrollBar"); doesn't exist until after changeScrollBar() is executed.
Using var scroll = '.verticalScrollBar' works because you're not declaring a nonexistent jQuery object. You're simply providing a bit of text, which CAN be matched to the object once it has been created.

jquery offset method doesn't always work / exist

Good morning and happy new year everyone!
I've run into a snag on something and need to figure out a solution or an alternative, and I don't know how to approach this. I actually hope it's something easy; meaning one of you all have dealt with this already.
The problem is that I'm doing rollovers that contain information. They're divs that get moved to the absolute location. Now I've tried this with jquery 1.6 - 1.9.1. Of course this has to work in multiple browsers.
What needs to happen is on rollover show a div, and when you rollout of that div, make it hide.
...
// .columnItem is class level and works
$(".columnItem").mouseleave(function() {
$(this).css("display", "none");
});
...
$(".column").mouseenter(function() {
var currentItem = $(this)[0]; // this is where the problem is
// hide all .columnItems
$(".columnItem").css("display", "none");
// i get this error: Object #<HTMLDivElement> has no method 'offset' (viewing in chrome console)
var offsetTop = currentItem.offset().top;
var columnInfoPanel = $("#column" + currentItem.innerText);
});
So the immediate thought of some would be don't use $(this)[0]. Instead, I should use $(this), and you are correct! Where the other problem comes into play is by removing the array index, currentItem.innerText is now undefined.
The only thing I can think of is I'll have to mix both, but it seems like there should be a way to use the selector and get both options.
What have you all done?
Thanks,
Kelly
Replace:
var currentItem = $(this)[0];
With:
var currentItem = $(this).eq(0);
This creates a new jQuery object containing only the first element, so offset will work.
Then you can use either currentItem[0].innerText or currentItem.text(), whichever you prefer.
Skip the [0] at the beginning as you are saying.
But then change the last line to:
var columnInfoPanel = $("#column" + currentItem[0].innerText);
De-referencing the jQuery selector gives you the DOM-object.
If you want to stick to pure jQuery, the .text() / .html() methods will give you the same functionality.

JQuery hide/show gone wrong

Here is a simplified example of what i'm working with, working around preexisting code:
Basically I have 2 divs I want to hide/show in multiple places(stage 1, stage 2, stage 3,etc), as so:
var blue_div = "#Blue";
var red_div = "#Red";
var blue_stage = "#Blue" + count;
var red_stage = "#Red" + count;
Adding insult to injury the div's exist elsewhere on page and are hidden. Need to pull the content into another div for each stage. So i'm using .prepend() to grab the content, as so:
var blue_html = $(blue_div).html();
var new_div = "#new_div";
$(new_div).prepend(blue_html);
$(new_div).attr('id', blue_stage); //Changing the id based on the stage
That last part is really whats throwing me...As now I'm trying to use the new_div without first ending the script so it's not yet in the DOM...
if ($(blue_stage).is(':hidden')) {
$(blue_stage).show()
$("#cancel").bind("click",function(){
$(blue_stage).hide()
}
}
I've seen a lot done with Window setTimeout() as well as setinterval and .queue(). But my attempts have all failed. Hopefully my example wasn't confusing, any help at all is appreciated!
I think you can do something like this:
var $new_div = $('<div id="' + blue_stage + '"></div>');
which will allow you to edit the element directly so you can do things like:
$new_div.prepend(blue_html);
to change the id you do:
$new_div.attr('id', blue_stage)
and note when your setting the id like this you don't need the "#" as the other answer mentions
Remember that you use the hash-mark # when selecting, but when setting as an ID on a node, you just use the identifier without this mark. So this line:
$(new_div).attr('id', blue_stage); //Changing the id based on the stage
Equates to this:
$(new_div).attr('id', '#Blue' + count);
But should perhaps be like this:
$(new_div).attr('id', 'Blue' + count);
(without the hashmark).
Hopefully your problem is as easily solved! Good luck!

Js - Append a value to element CSS

This seems so simply yet its not working (undefined).
I have set a var to <ul> which is a child of <div> element "feature_tabs_indicators".
The pBoxShadowProperty function gets the BoxShadow property supported by the current browser.
And the final statement merely sets the pBoxShadowProperty to 0, i.e. its overriding the CSS set Box-Shadow property.
Can someone please explain what I am doing wrong here in the last statement?
Best,
var iActiveNo = 0;
var eTabInd = document.getElementById ("feature_tabs_indicators").children[0];
var pBoxShadowProperty = getSupportedCSSproperty(["boxShadow", "mozBoxShadow", "webkitBoxShadow"]);
function getSupportedCSSproperty (propertyArray)
{
var root = document.documentElement;
for (var i = 0; i < propertyArray.length; i++)
{
if (typeof root.style[propertyArray[i]] === "string")
{
return propertyArray[i];
}
}
}
iActiveNo = iActiveNo + 1;
eTabInd.children[iActiveNo - 1].style[pBoxShadowProperty] = "";
Here is the jsfiddle, press the light green button 'rght' on top right.
I think I figured out what your issue is. You use here:
iActiveNo = iActiveNo + 1;
something that has not been defined in your posted code. However you do have:
var iActive = 0;
which I think should have actually been:
var iActiveNo = 0;
otherwise your code has JS error in it (as it is posted, anyway).
Other than that (that is, if your intention was to take the 1st <li> element out of the <ul> element and remove its box-shadow CSS property) - your code is just fine.
Edit
Dude, what a mess.. :) Here is a JSFiddle I fixed up a bit. Below is the explanation.
There are several things going on in that JSFiddle that should be fixed before we get to the real problem.
You have errors in that fiddle - see console. The line:
var pBackgroundColorProperty = eStyle.backgroundColor //[pBoxShadowProperty];
doesn't end with a semicolon, and is then interpreted as a function due to (..) on the next line (I think) - which (for me at least) results in an error in JS console. If semicolon is added - error is gone.
Additionally... There is a line:
console.log (eTabInd.children[iActiveNo-1].style.pBoxShadowProperty);
which prints your undefined and is exactly what was discussed below and should be
console.log (eTabInd.children[iActiveNo-1].style[pBoxShadowProperty]);
which then prints the empty string.
Moreover, when printed, your pBoxShadowProperty variable contains boxShadow string. Which is, of course, not a valid CSS property I am familiar with. So this:
eTabInd.children[iActiveNo - 1].style[pBoxShadowProperty] = "";
won't do a thing.
Now to the meat of the issue here...
eTabInd.children[iActiveNo-1].style
doesn't have 'box-shadow' property to begin with, because you haven't put it in style attribute of <li> element. It is put on the <li> element through the virtues of this CSS selectors sequence: #feature_tabs_indicators ul #ind_bt.
Now, since you wanted the style attribute - you won't get the computed style the above CSS selectors sequence applies. Thus - you won't be able to remove it.
What you could have done is create another class, that doesn't have a box-shadow property and replace your original c_ind with it.
it looks like you have not set value correctly as it should be like
eTabInd.children[iActiveNo - 1].style.pBoxShadowProperty = "";
Dose that help or dose still return 0?

jquery / javascript - Simple split() problem

if ($(".productpage .description").html() != null) {
var textToHide = $('.productpage .description').html().split('<br class="breakHere">')[1];
var visibleText = $('.productpage .description').html().split('<br class="breakHere">')[0];
}
Works great in Firefox, but in IE and Chrome textToHide and visibleText are undefined. Did I miss something? Thanks
View your $('.productpage .description').html(), you may be getting <br />
Using split() against HTML isn't a good idea IMHO - it's too brittle, and is likely to suffer the same problems as using Regexp's against HTML.
Assuming that the elements you're trying to split are all siblings with the <br> element, try this:
var $el = $('.productionpage .description'); // find the element
var $br = $('br.breakHere', $el); // find the BR inside it
var $vis = $br.prevAll(); // contains everything before the break
var $hide = $br.nextAll(); // contains everything after the break
Note that this will give you jQuery objects containing those elements, not the HTML text of them.

Categories

Resources