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.
Related
I have dynamically created elements on the page, a picture and three buttons which are created upon clicking the main button.
All of this works, but now I am trying to change the display on the dynamically created div with the pics to "none".
More than one issue arises here for me, first I cannot find out how to make the div "images" the target, or select it.
I am trying to get one function to do this for all the elements, they are all structured equally just the pictures are different.
function hidePic(arrayPos){
var elem = document.getElementsByClassName("closingButton") + "[" + arrayPos + "]",
finalTarget = elem.getElementsByClassName("images")[0];
finalTarget.style.display = "none";
}
document.getElementsByClassName("closingButton")[0].addEventListener("click", function(){
hidePic(0);
});
This is the relevant code, lines 4 to 10. If this is commented out, the rest of the code works, but as it is I get entirely unrelated errors in dev Tools.
Click this link to see Codepen.
So the question is, how can I best implement the above code?
So just working on the code above you can do this in order to make it work for all instances. First let me point out that this:
var elem = document.getElementsByClassName("closingButton") + "[" + arrayPos + "]";
will never work. That line is building a string. What you really want to make that line work is:
var elem = document.getElementsByClassName("closingButton")[arrayPos];
But even that I find unnecessary. Take a look at this code.
function hidePic (elem) {
var finalTarget = elem.getElementsByClassName("images")[0];
finalTarget.style.display = "none";
}
var closingButtons = document.getElementsByClassName("closingButton");
var index = 0, length = closingButtons.length;
for ( ; index < length; index++) {
closingButtons[index].addEventListener("click",
function () {
hidePic(this);
}
);
}
This first finds all elements with the class closingButton. Then for each one we attach a click event listener. Instead of attempting to pass some index to this hidePic function we already have our function context which is what you seem to be trying to find in the function so lets just pass that and use it to find the image inside.
Let me know if you have any questions. I took a look at your codepen as well. I am not sure you should be forcing all that interactive HTML into a button element honestly, which itself is considered an interactive element. Not sure that meets the HTML spec. Perhaps add that HTML below the button. I bet when you click on things inside of that button it will register as clicks on the button as well unless you remove the event upon inserting your elements but then it seems like its getting too complicated for the simple stuff you are trying to do here.
The codepen complains because there is no element with the "closingButton" class, so it's trying to call addEventListener on nothing, but I'm doubting that's the actual error you're seeing.
It's also worth nothing that I think this:
var elem = document.getElementsByClassName("closingButton") + "[" + arrayPos + "]",
is excessive.
var elem = document.getElementsByClassName("closingButton")[arrayPos];
should be sufficient. Also not the syntax error at the end of the same line: it should be ; not ,. If this is the error in your code it could explain why you were getting "unrelated errors" syntax errors can cause misleading problems that are supposedly in other areas of the code!
Lastly, I'd highly recommend using JQuery to do your selection magic - it's exactly what it was designed for. If you're averse to using JS libraries, fair enough, but it would make your code a lot simpler and you can have reasonable confidence that it will perform the tasks about as optimally as is possible.
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.
I am working on a slider that uses jQuery. Some elements of the slider are working correctly, but there is a problem that I am trying to troubleshoot with some of the code. To test it I would like to be able to display the values of the variables in the statement.
Here is the code block I am working with:
$('.marquee_nav a.marquee_nav_item').click(function(){
$('.marquee_nav a.marquee_nav_item').removeClass('selected');
$(this).addClass('selected');
var navClicked = $(this).index();
var marqueeWidth = $('.marquee_container').width();
var distanceToMove = marqueeWidth * (-1);
var newPhotoPosition = (navClicked * distanceToMove) + 'px';
var newCaption = $('.marquee_panel_caption').get(navClicked);
$(' .marquee_photos').animate({left: newPhotoPosition}, 1000);
});
I added a div called 'test' where I would like to display the values of the variables to make sure they are returning expected results:
<div class="test"><p>The value is: <span></span></p></div>
For example, to test the values, I inserted this into the statement above:
$('.test span').append(marqueeWidth);
However, I don't get any results. What is the correct way to include a test inside that code block to make sure I am getting the expected results?
Thanks.
Just use JavaScript's console functions to log your variables within your browser's console.
var myVar = 123;
console.log(myVar, "Hello, world!");
If you're unsure how to open the console within your browser, see: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
append is used to append either an HTML string, a DOM element, an array of DOM elements, or a jQuery element. Since you are just trying to show a number (marqueeWidth), you probably want to set the text of the span instead:
$('.test span').text(marqueeWidth);
Also, is there a particular reason why you don't just use the console? It may be worth reading over a Debugging JavaScript walkthrough.
you can use the following.
$('.test span').html(marqueeWidth);
However doing a console.log(yourvariable); or alert(yourvariable); is better.
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!
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?