JQuery hide/show gone wrong - javascript

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!

Related

One function for many buttons

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.

jquery replace the content of a div persistently

I am trying to replace the content of a div tag with a certain value every 50sec via polling and jQuery. And I would like to access the value of that updated div, so I can save a request to the backend.
My problem is that once the content has been replaced, the browser displays it correctly, however the HTML stays the same as the beginning. I'm afraid this is a rather basic question, but I'm really curious about this.
Here I prepared an example to illustrate the issue: http://jsfiddle.net/LJgN6/7/
And you can see it out ot JSfiddle's context to check the final HTML here: http://jsfiddle.net/LJgN6/7/show
I would like to achieve a way to have in the final HTML(i.e. right click, view page source):
num 1.1 replaced with num 1.2
num 2.1 replaced with num 2.2
...
The code that you see in the View Source window is the HTML that was sent to the browser before anything client side was allowed to modify the DOM. If you want to see the source as it is modified by your javascript, you need to inspect the DOM (IE F12, Firebug, etc.)
If you need to access this value that was inserted earlier, using javascript to access the contents of your element (ie. $('#number-2').text()) should return its contents as they are currently in the DOM.
EDIT: Corrected typo
It looks like you're already familiar with jQuery so I would go ahead and head over to the extremely helpful API and take a look at AJAX calls. There is plenty of documentation there that will help you.
http://api.jquery.com/jQuery.ajax/
Here's an idea. Take a look at my fiddle of your problem
$(document).ready(function(){
$('#number-1').html("num " + 1.1);
$('#number-2').html("num " + 2.2);
$('#number-3').html("num " + 3.3);
$('#number-4').html("num " + 4.4);
setInterval(function(){newInfo();}, 3000);
});
function newInfo(){
var firstDiv = $('#number-1');
var secDiv = $('#number-2');
var thdDiv = $('#number-3');
var frthDiv = $('#number-4');
var firstDivInfo = firstDiv.text().substr(4);
var secDivNewInfo = firstDiv.text().substr(4);
var thdDivNewInfo = secDiv.text().substr(4);
var frthDivNewInfo = thdDiv.text().substr(4);
var newNumber = (Math.random() + 1).toFixed(1);
secDiv.html("num " + secDivNewInfo);
thdDiv.html("num " + thdDivNewInfo);
frthDiv.html("num " + frthDivNewInfo);
firstDiv.html("num " + newNumber);
}

jQuery width() not working

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!

How do I access elements in jquery if the id is based on one of the function arguments?

I am trying to access an element in jquery using a function input. To clarify, here is an example of what I have tried that isn't working:
function openReceivedMessage(messageid)
{
// ajax post query that is executing fine
// set row to not be highlighted
var rowid = 'receivedrow' + messageid.toString();
document.getElementById(rowid).style.background-color = "#ffffff";
// other code that is executing fine
}
Essentially, this is for a message inbox page. I have displayed the messages in a table, and, as the number of messages changes for each user, I used a loop to populate it. In order to open a message, I have hoped to use a jquery function (titled above), and so when the loop populated the tables, I set it so that each of the different subject lines would, onclick, execute the above function with the unique messageid passed in as the argument. Upon opening, I want to change other things in the table (that I named, similar to the message function, as things like 'receivedrow#' where # is the messageid.
Would hugely appreciate any help here, I feel like there must be a simple way create a string (like I did with rowid above) and access the element with that id (in the table there is a row with id="receivedrow#" that I want to adjust the css of).
I recommend using jQuery to find the element
var rowid = 'receivedrow' + messageid.toString();
var $el = $("#" + rowid);
Then simply operate on $el
$el.css({'background-color':'#FFFFFF'});
If you're having trouble still, I recommend checking that rowid is correct and that the jQuery is then giving you the right element back.
function openReceivedMessage(messageid)
{
var rowid = 'receivedrow' + messageid.toString();
var $el = $('#'+rowid);
$el.css({'background-color':'#FFFFFF'});
// other code that is executing fine
}
Seems what you have posted is not jQuery at all :D
It is simple JavaScript trying to get a DOM element with id rowid. It does not works maybe be because of following two reasons:
there is no element with id rowid which you can easily verify.
background-color is not a property its backgroundColor.
Try using this:
document.getElementById(rowid).style.backgroundColor = "#ffffff";
If you what you really need is an easy way get the id onclick, then simply use the this keyword in your row markup.
onclick="openReceivedMessage(this);"
Then access in your function as such:
function openReceivedMessage(row)
{
// set row to not be highlighted
var rowid = 'receivedrow' + row.id;
$('#' + rowid).css({'background-color':'#ffffff'});
}

jQuery- .css() not working for an input

This should be a really simple problem, but I can't quite figure out what I am doing wrong. I am trying to access the CSS property 'border-bottom' like this:
var temp = $('#divName').css('border-bottom');
Unfortunately, after this, temp contains the string ""
Does anyone know why this is not working or what I should do differently to make it function? Thanks.
The styles have to be more specific. Since border-bottom is a short-property for other properties (similar to background, to name a common one), the property has to be explicitly given.
var elem = $('#divName');
var border_width = elem.css('border-bottom-width');
var border_color = elem.css('border-bottom-color');
var border_style = elem.css('border-bottom-style');
var border_bottom = border_width + " " + border_color + " " + border_style;
Fiddle: http://jsfiddle.net/6wRj4/
See also: MDN: border-bottom short-hand.
Check to ensure that $('#divName') does select a single element. You can use array syntax on a jquery object to get back the underlying DOM object. You should also check (for example, using Firebug) to make sure that the DOM element you're looking at does have the style that you're looking for.
If both of those things are working correctly, you might try using the more granular border properties... border-bottom-style, border-bottom-width, etc.
Try with document.getElementById("divName").style.borderBottom;.

Categories

Resources