Href attribute using variable does not work - javascript

In JS, I am creating a link where the href attribute runs a function. The function simple opens an alert window with a given variable.
function alerter(str){
alert(str);
}
When I create the link, I use the following code.
var link = document.createElement('a');
link.setAttribute('href','javascript:alerter("hi")');
link.innerHTML = "Sauce";
If I do that, it works. However, what I want to do is alert a previously defined variable. But when i use
link.setAttribute('href','javascript:alerter(myvar)');
the popup no longer works. Also, is there a way to simply embed the alert in the href instead of writing a separate function?

It should be
link.setAttribute('href','javascript:alerter("' + myvar + '")');
You're using string concatenation to put myvar into that string. The way you had it, the whole thing is a string "javascript:alerter(myvar)"

Try this
link.setAttribute('href','javascript:alerter('+myvar+')');

The myvar variable has to be in the global scope. Be sure you can also access it as window.myvar.

for your first question use :
link.setAttribute('href','javascript:alerter(' + somevar + ')');
and for your second question use:
link.setAttribute('href','javascript:alert(' + somevar + ')');
cheers.

http://jsfiddle.net/xmBbw/2/
Just modify the onclick event of your anchor. If you are not going to link anywhere, you need not use the href attribute. Rather use onclick and assign any function you like to it. Besides, it's awfully bad practice to write javascript inside an html tag. Please don't.
A nice article regarding good practices

Related

How to pass javascript url parameter in this script through html dom?

I want to pass url parameter through html dom. This is the javascript i am using
<script>
function myFunction(url)
{
setTimeout(function(){window.location.assign(url)},4000);
}
</script>
HTML
Click here
But its not working. How can i fix this situation ? Thanks for your answers.
Use combination of single and double quotes, to pass the url as string literal. If the url is not enclosed in quotes it is considered as some variable and javascript could nod find that.
Click here
As #Adil says, you need to pass the argument as string to the function. In the way you are trying, the script is trying to recover the value of the http://stackoverflow.com variable.
what #Adil has said is true:
Click here
but if you want to pass the url as a parameter do not forget to change your function like this:
function myFunction(url)
{
setTimeout(function(){window.location.assign(encodeURIComponent(url)},4000);
}

Using jQuery `.attr()` outside the scope of a `.each()` - possible?

I want to change the first element with class .viewer's src attribute to the value of it's data-src attribute. The obvious code doesn't work:
$(".viewer").first().show().attr('src', $(this).attr('data-src'));
From reading other question on SO, I find you have to do this:
$(".viewer").first().show().each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
It does work, and I do understand why (this doesn't refer to the element outside of the scope of the .each) - but it seems very weird to run .each() after you've already used .first().
Is there a cleaner way to write the above code?
Store data you want to reuse in a variable.
var viewer = $(".viewer").first().show();
viewer.attr('src', viewer.data('src'));
You can always just use a variable:
var elem = $(".viewer").first();
elem.show().attr('src', elem.attr('data-src'));

run jQuery function by inline onClick and use function variable/reference

I am very new to this, but I wrote this and thought it would work first time, but I get an 'ReferenceError: Can't find variable: street' console error.
I get this error if I click on the 'Street' button.
It's quite basic but this is the first time I've made a function to use a var/ref from the onClick attribute.
Please see onClick markup...
Supersport
Street
Cruiser
Scooter
Motocross
Enduro
Kids
then please see my function, which gets the ref error above...
Also please note I am trying to use the onClick var/ref within my function so I can target specific elements relative to the button being clicked.
bikeFilter = function (y) {
$('.bike').fadeOut();
scrollTo(186);
$('.bike[data-group=' + y + ']').fadeIn();
bikeSliderNav();
bikeSlider();
return false;
}
Any expert advice would be really helpful.
Thanks in advance.
You'd probably wanna pass a String as input to your function and not the name of an undeclared and uninstantiated variable.
Try to use the single quotes to refer it as a String constant (you need single quotes since you are already using double quotes to tell your html tag the attribute value):
onclick="bikeFilter('scooter')"
Take a look here to see the difference in data typing in js, and here for a quick start about functions.
You should use them like :
onclick="bikeFilter('motocross')"
Don't forget to put ' around your parameters

Javascript syntax to pass variables

Still muddling my way through Javascript, I'm trying to pass the contents of variable playnoyes to the long line of code below to decide whether or not to autoplay the flash movie, but doing it as I have below, the resultant line of code has the variable in quotes and therefore the code doesn't execute it as expected. My question is, how can I pass the variable so that the resulting line of code doesn't have the quotes around the variable value.
Many thanks, and sorry for the noobness of the question.
var playnoyes='true';
var testtext = "<script type='text\/javascript'>AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=\""+playnoyes+"\"&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer');<\/script>";
alert (testtext);
Thats because you are explicitly adding the quotes:
change
nigel&autoPlay=\""+playnoyes+"\"&autoRewind=true'
to
nigel&autoPlay=" + playnoyes + "&autoRewind=true'
Try this:
var playnoyes='true';
var testtext = "<script type='text\/javascript'>AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay="+playnoyes+"&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer');<\/script>";
alert (testtext);
Remove the two '\"' on each side of the variable, no?

Extracting the javascript from an anchor's href using jQuery or JavaScript

Does anyone know an easy way to use jQuery (or other Javascript if necessary) to extract only the Javascript portion of an anchor tag's href attribute (like the one below), so it can be assigned to another event at runtime?
<a id="FancyLink" href="javascript:DoSomething('Input1')">Do</a>
I know how to get the anchor's whole attribute value using jQuery, and I suppose I could just do that and then chop off the "javascript:" prefix manually, but I'm wondering if there is a better way to obtain a JavaScript function object from the above example.
Thanks for the help!
Brian
Like this:
var code = $('#FancyLink').attr('href').replace(/^javascript:\s*/, '');
This will return a stringm which you'll need to eval in order to execute.
For better performance, you can call eval once and create a function, like this:
var executor = eval('[ function() { ' + code + ' } ]')[0];
The array is necessary because IE cannot directly return a function from eval.
For even better performance, don't do this at all.
Assuming you can't refactor the <a href="javascript:..."> code, which is the problem here, you could also assign the href to location, which is roughly what happens when user clicks the link anyway. That would save you chopping off the 'javascript:' portion and would be a bit more natural.

Categories

Resources