First post here, so please be gentle ;-)
I've been learning coding over the last couple of weeks by making a dummy page, and been implementing what i learn on it incrementaly as i progress, hence it's a mixed bag where the functionality/code is according to when i wrote it, based on pure html/CSS, inline javascript, external javascript, and finally jquery.
So i mostly wrapped it up and i'm now cleaning up the mess, and part of my mission is to cull functions and lines of codes, and in one of them i'm kind of stuck.
The before was 30 buttons calling to 30 different functions onclick like so:
function cell3() {
document.getElementById('base3').src='images/1/3/' + x + '.png';
document.getElementById('base3b').src='images/1/3/' + x + '.png';
document.getElementById('v2base3').src='images/2/3/' + x + '.png';
document.getElementById('v2base3b').src='images/2/3/' + x + '.png';
document.getElementById('cell3').style.backgroundColor= x ;
}
Where a global variable (x) defines the folder paths for images to replace the images within some divs when clicking the button (cell3). It also changes the bGroung color of it. Sorry if the naming is a bit confusing...
So i'm removing all 30 functions and the 30 onclick calls with this bit of jquery:
$('button').click(function(){
var eyeD = $(this).attr("id");
var newURLa = 'images/1/' + eyeD + '/' + x + '.png';
var newURLb = 'images/2/' + eyeD + '/' + x + '.png';
$('base' + eyeD).attr('src', newURLa);
$('base' + eyeD + 'b').attr('src', newURLa);
$('v2base' + eyeD).attr('src', newURLb);
$('v2base' + eyeD + 'b').attr('src', newURLb);
$(this).css( "background-color", x );
document.getElementsByid('check').innerhtml = eyeD;
});
For that to 'work' i changed the button's names from 'cell1', 'cell2, etc. to '1', '2', etc.
Now the thing is, when clicking on the buttons the var 'eyeD' takes the value from the button ok. ('1', '2', etc.). The elements ID's are formed correctly ('base1', 'base2'... 'base1b', base2b'...), and the URL's are formed correctly. (The last line in the code is a p element that displays values so i could try to troubleshoot it) The background color also changes as expected. But the images do not get replaced.
Tried adding commas to the resulting URL's in case it was a syntax issue, but nothing happens. i even went freestyle and tried it with the =url() on it, different commas in different places, etc. So basically scraping the barrel here. Also wrote a url without variables to see if that would work, but still nothing. Also getting no errors when looking at the console.
It's probably a basic 'DOH!' thing, but right now i have a mental block...
Also, is there a way to keep the original naming and just retrieve the numbering part of the ID's? Thought about using the [4] identifier to get the 5th digit, but that won't work when running double digit numbers. (10, 11, etc)
Thanks!
Your jQuery lines accessing the elements are missing the # sign.
Change these...
$('base' + eyeD).attr('src', newURLa);
To this...
$('#base' + eyeD).attr('src', newURLa);
Also, your last line where you use plain JS, can be done in jQuery as well with less code.
document.getElementsByid('check').innerhtml = eyeD;
To...
$("#check").html(eyeD);
However, you should always use distinct ID's for elements. If you need to use multiple elements at the same time, use a class instead.
$(".check").html(eyeD);
You're grabbing an element incorrectly.
Either Grab an element by it's class name like so:
$('.v2base' + eyeD + 'b').attr('src', newURLb);
Or by its ID:
$('#v2base' + eyeD + 'b').attr('src', newURLb);
Problem solved!! It was indeed calling the id with the hash, but also it has to be called with double quotation marks. Single inverted commas won't work.
So the working format is
$("#v2base" + eyeD + "b")
but it won't work like so
$('#v2base' + eyeD + 'b')
Thanks everyone, it's been emotional
Related
I am pretty confident that this can be done but my efforts so far have failed. I have a loop generated series of divs that have id=x0, x1, x2 etc.... Depending on context the html of one or more div(s) will be reset. In the case where two divs will have the same value, and the id is a known number I would easily do:
$('#x3, #x7').html('new value');
How to set this when the id number is a variable? I first tried:
$('#x'+(location-2), '#x'+(location+3)).html('new value'); // doesn't throw a console error
// but doesn't work
I tried numerous permutations involving quotes, escaped quotes, brackets {}, [], () - in combination with quotes, etc. etc. hair pulling etc.
To keep the project moving I am declaring multiple replacements which is no great extra load but it would be tidier to have a single call -- and, I always look to learn.
Seems like a common class would be a better solution to this, but to answer your question, you didn't concatenate properly:
$('#x' + (location-2) + ', #x' + (location+3)).html('new value');
jsFiddle example
And you also may run into issues using location as a variable name as it's a property of the Window object.
Just create an array of selectors and then join them:
var selectors = [
'#x' + (location - 2),
'#x' + (location + 3)
];
var jointSelector = selectors.join(',');
After concation it should look like '#x3, #x7'. But here you are not concating the comma. That is the mistake you are doing.
$('#x' + (location-2) + ', #x' + (location+3)).html('new value');
you miss the apostrophe
$("#x"+(location-2)+",#x"+(location+3)).html('new value')
I'm writing a function for creating images from an array and I need to put some extensive HTML inside a javascript string. Unfortunately whenever I use parentheses, it throws off the whole thing.
Any help?
This:
listItem.innerHTML = "<img src='" + listData[i] + "'>"; */
This doesn't:
listItem.innerHTML = "<div class='item square' style='background-image: url(" + listData[i] + ")'></div>";
Your code depends on listData[i] being valid when tossed into three places:
CSS’s url()
CSS
HTML
It shouldn’t. Building HTML in JavaScript isn’t a very good idea in the first place. If you truly have enough markup that must be built dynamically that you can’t use the DOM, use a template engine that knows its target. In this and most cases, use the DOM!
var itemImage = document.createElement('div');
itemImage.className = 'item square';
itemImage.style.backgroundImage = 'url("' + encodeURI(listData[i]) + '")';
listItem.appendChild(itemImage);
This creates one element, assigns values to some of its properties, and appends it to listItem, and it will always do that; you don’t have to hope that your quotes matched up properly or that you remembered to escape absolutely everything.
Footnote: the combination of encodeURI and double quotes around the url() value will almost certainly fix any potential problem – quotes or parentheses – regardless of which method you use to add them, but that doesn’t mean you should keep using innerHTML.
Whereas I have plenty of experience with PHP coding, I am pretty new to using javascript so I hope this question doesn't come off as stupid.
My goal here is to create a button that when pressed causes the background-position in a defined DIV object to alter its background-position by one pixel.
I've been doing a lot of searching on Google as well as this site in particular and following the tips I have found I've been playing around with the javascript functions a lot but I can't seem to get one that works the way I need it.
My current incarnation looks like this:
<SCRIPT TYPE="text/javascript">
var xObject = 0; // Global
function xMinus(ele) {
xObject-=1;
document.getElementById(ele).css({ 'backgroundPosition': xObject + 'px ' + 0 + 'px' });
}
</SCRIPT>
Where the goal is upon clicking the button (containing onclick="javascript:xMinus('divID');" ) the background should shift to the left by one pixel.
However currently when I click it, Error Console gives me "Error: document.getElementById(ele).css is not a function".
I've tried a few different variations but always get similar results, or "Variable is not defined". Clearly I have no idea what I am doing. Please help! I am coding this for friends and do not want to keep them waiting too long.
If you are not using jQuery then,
document.getElementById(ele).style.backgroundPosition = xObject + 'px ' +'0px';
What are you passing inside the ele? It should be a string of the id of the element and it shouldn't start with a number.
Try rewriting the code this way:
var xObject = 0; // Global
function xMinus(ele) {
xObject--;
$('#'+ele).css({ 'backgroundPosition': xObject + 'px ' + 0 + 'px' });
}
I hope you are using jQuery! :) If not using jQuery, it should be:
document.getElementById(ele).style.backgroundPosition = xObject + 'px ' + '0';
And for the handler, that <a> tag, the code should be: (shouldn't contain javascript:)
BG Left Push!
I have got this link:
Visit imLive.com
I want to use this code to add/change different url parameters:
$("a.sitelink_external.imlive").each(function(){
$params=getUrlVars(document.URL);
var promocode_addition='';
if('INFO'==$params['ref']){
promocode_addition='LCI';
}
$(this).attr("href", 'http://im.com/wmaster.ashx?WID=124904080515&cbname=limdeaive&LinkID=701&queryid=138&promocode=LCDIMLRV" + i + promocode_addition+"&"FRefID=" + FRefID + "&FRefP=" + FRefP + "&FRefQS=" + FRefQS');
});
The problem is that that jquery code doesnt work..I tried to move it to document ready..but it doesnt work there too..
The thing that jumps out at me is that you're mixing your double and single quotes on this line:
$(this).attr("href", 'http://im.com/wmaster.ashx?WID=124904080515&cbname=limdeaive&LinkID=701&queryid=138&promocode=LCDIMLRV" + i + promocode_addition+"&FRefID=" + FRefID + "&FRefP=" + FRefP + "&FRefQS=" + FRefQS');
Try changing them all to double quotes, and remove the extra " from after the ampersand in "&"FRefID=" - like this:
$(this).attr("href", "http://im.com/wmaster.ashx?WID=124904080515&cbname=limdeaive&LinkID=701&queryid=138&promocode=LCDIMLRV" + i + promocode_addition+"&FRefID=" + FRefID + "&FRefP=" + FRefP + "&FRefQS=" + FRefQS);
The way you had it was a single string containing stuff that looked like code. The way I've changed it is several strings and variables being concatenated together... (Note the difference with StackOverflow's syntax highlighting.)
Note also that the following code:
$params=getUrlVars(document.URL);
var promocode_addition='';
if('INFO'==$params['ref']){
promocode_addition='LCI';
}
...can be moved to before the .each() loop, since it operates only on the document and thus will produce the same results on every iteration.
(Of course there could be other problems since you reference several variables that aren't shown.)
I'm trying to disable/enable multiple form elements of an HTML page using javascript. I have a form with many fields, each row of the form has a checkbox to enable/disable the elements on the row.
The problem is, only the first two form elements get disabled (no matter the order). After that, the remaining javascript code in the function just won't be executed anymore.
Here's the code (it's part of a function called by the onChange attribute of every checkbox):
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_quantity")[0].disabled = !theBox.checked;
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_description")[0].disabled = !theBox.checked;
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_price")[0].disabled = !theBox.checked;
document.getElementsByName(prefix + "fase" + phaseNumber + "_" + objectNumber + "_language")[0].disabled = !theBox.checked;
Each form element has a different (and unique) name, and the single lines of code work just fine... until you put them together.
For example: in the above code, "quantity" and "description" fields will get disabled/enabled, but "price" and "language" won't.
If i change the order of the lines, the first two get always executed, no matter what.
Then every line of code doesn't work; it's like it's commented. I even put some alerts to try debugging, but they just get ignored (no dialog shows up at all) if I insert them after the above code. The elements names are correct.
I'm sure I've made a mistake somewhere, but since the single lines of code are working, I don't know where to look... it's driving me nuts!
Please, I could really use some help.
I just made it work and, as I thought, it was a very bad mistake.
The problem was, not every form row in the HTML has all of those 4 fields. So, basically, I was trying to access a property of a null object.
I solved it by putting:
if( document.getElementById(id) != null )
before trying to manipulate the element.
Sometimes when you're in a hurry, you end up neglecting some very basic stuff...
Thank you for your time.