HTML/Javascript use src string in onclick without retyping? - javascript

I want to use the same string in my img "src" in my "onclick" as a parameter to a function. What's the easiest way to do this? It works fine if I type it out both times but it doesn't look nice.
Here is an example so you can see what I mean...
<img src="/images/image1.jpg" onclick="doStuff('/images/image1.jpg')"/>
I'm wondering if there is a simple way to have the src in the onclick too that doesn't require me to write it out again? So I can use a general onclick for each image that needs to be clicked.

<img src="/images/image1.jpg" onclick="doStuff(this.src)"/>

doStuff(this.src);

The easiest thing is to pass the object itself into the function. So:
<img src="/images/image1.jpg" onclick="doStuff(this.src)">
Will do what you want, I believe.

Related

What's better to use in Angular - src or [src]

Just want to ask what is recommended to use with Angular, standard html src or Angular [src]? And why?
Edit: I have following code in my html component:
<img class="logo" src="../app/media/appLogo.png">
It is fine? If not, how should I change it to work together with [src]?
Edit2: Is there any other, better way to do it, instead of plain html src? Or this is the best solution actually?
[...]="..." is for object binding ...="{{...}}" is for binding with string interpolation. If you want to bind a string it doesn't matter what you use. If you want to bind an object or array value you need to use `[...]="...". Besides that it's entirely up to you.
<img class="logo" src="../app/media/appLogo.png">
Is not related to Angular2 at all, thats just plain HTML (no [] and no {{}}). If you add [] around src, then Angular will treat ../app/media/appLogo.png as an expression, which it clearly isn't.
When DomSanitizer is used [src]="..." is mandatory because the value no longer is a string, but an object and using {{}} would stringify it in an invalid way.
Using regular src sets the Attribute where setting [src] sets the property. Considering that for an image (I assume you're talking about an image but you don't say) the src attribute is used to set the corresponding property they will both work.
There is one big reason to use [src] though. Browsers tend to start downloading whatever you put in the src attribute while parsing the html. So lets say you do this:
<img src="{{myImgSrc}}"/>
The browsers will often immediately start downloading {{myImgSrc}}, which will lead to a 404 in the console. Using the following is therefor slightly better:
<img [src]="myImgSrc"/>
If you have static anchor link, then go ahead with
<img class="logo" src="../app/media/appLogo.png">
When binding from the component, then either of the below will work.
<img class="logo" [src]="image_src">
<img class="logo" src="{{ image_src }}">
In component.ts
image_src: string = '../app/media/appLogo.png';

JS function does not respond to event onclick

Hi guys I have a a problem I think is a easy one but I don't find the problem. I have a "menu" where I want to send a data to another page when I click one button. So I write a function in js to open a new tab and the send the data. But when I do click, it is like if the function doesn't exist.
<div id="botones">
<input type="button" value="<?=L::misc_export?>" onclick="javascript:pasarDatosParaExportar();" name="boton" />
</div>
<script type="text/javascript">
function pasarDatosParaExportar() {
window.open('calculos.exportar.php?fecha2='+'<?=$_POST['fecha2']?>'+'&hasta='<?=$_POST['hasta']?>'&cuartel='<?=(int)$_GET['cuartel']?>'','_blank');
}
</script>
Remove javascript: from content of your "onclick". It's for <a href="[HERE PUT javascript:]"
If you have link and want to put JS code into "href" parameter, should use it:
click
But you can do the same like this:
<a onclick="alert('success!')">click</a>
You should check the string delimiter characters (') in the parameter to the open function. I guess you probably mean to write something like this
function pasarDatosParaExportar() {
window.open('calculos.exportar.php?fecha2='+'<?=$_POST['fecha2']?>'+'&hasta=<?=$_POST['hasta']?>&cuartel=<?=(int)$_GET['cuartel']?>','_blank');
}
Write the JavaScript code to define the function before its use in the div and above in code because html assumes that this code doesn't exists if it doesn't occur before its use. So just replace the div and script with each other. This should work fine. And there is no need to use javascript: before name of function. yo can use onclick="pasarDatosParaExportar();".

Cant get an attribute of an element with jquery

I have got this html:
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
I am trying to get this:
$('body').on('click','.hostPic',function(){
console.log($(this).attr('data-name'));
});
Whenever the picture is pressed, I want to gets its data-name attribute, but it doesnt work.. I get undefined reported when I try to retrieve the attribute. Any reason why?
Add the hostPic class to that image.
Additionally, you can just use .data('name'), but it doesn't actually make a difference. Older browser may have trouble with .data, but it's never been a problem for me.
$('.hostPic').click(function() {
console.log($(this).data('name'));
}
Make sure your image has the class 'hostPic' and then do the following in your jQuery:-
$('.hostPic').on('click', function() {
console.log($(this).data('name'));
}
The following code worked for me, maybe you are attaching the events wrong object, you can understand that by debugging the this object instead of data-name.
And another thing is if you are going to use .data just for read string you should use .attr as the .data caches and tries to convert the value its appropriate type like number or JSON it is a heavier process than .attr.
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">​
​$("img")​.click(function () { alert($(this).attr("data-name")); });​

trying to access rel attribute of <a> using javascript

I am using an javascript overlay in my site for my subscription form. I have loaded the code for overlay from net. It is in javascript. Now the thing is to trigger the overlay function using a link i need put some value under <a rel="">.
more specifically, click
But i dont want to put a tag instead i want to link to the subscription page using javascript function. Now my problem is how or where do i put the value under 'rel' attribute in my javascript to get the same result???
Like this:
A
If you want to use plain JS without jQuery, try setAttribute: https://developer.mozilla.org/en/DOM/element.setAttribute
Give your tag an id attribute and then you can add:
document.getElementById("your_id").setAttribute("rel", "gb_page_center[450, 450]");
Using jQuery, this can be accomplished quite cleanly by using the .attr() method:
$('a').attr('rel', 'gb_page_center[450, 450]');

How to add an HTML attribute with jQuery

Well, I have this jQuery image slideshow that uses the attribute "control" inside an <a>. Seeing how it didn't validate I searched for a way to add this attribute inside my HMTL via jQuery but I didn't really find anything relevant. Now I don't really care about how valid my page is, but I'm really curious in how to add an HTML attribute inside an HTML tag.
In case I wasn't clear enough with my explanation, I have this code:
<a id="previous" control="-6" href="#"></a>
And I want to add control="-6" with jQuery.
Use jQuery's attr function
$("#previous").attr("control", "-6");
An example
// Try to retrieve the control attribute
// returns undefined because the attribute doesn't exists
$("#previous").attr("control");
// Set the control attribute
$("#previous").attr("control", "-6");
// Retrieve the control attribute (-6)
$("#previous").attr("control");
See this example on jsFiddle
You can alternatively use data function to store values on elements. Works the same way, for example:
$("#previous").data("control"); // undefined
$("#previous").data("control", "-6"); // set the element data
$("#previous").data("control"); // retrieve -6
Using data you can store more complex values like objects
$("#previos").data("control", { value: -6 });
($("#previos").data("control")).value; // -6
See a data example on jsFiddle
Since the jQuery version has been well covered here, I thought I'd offer something different, so here a native DOM API alternative:
document.getElementById('previous').setAttribute('control','-6');
Yes, I know you asked for jQuery. Never hurts to know the native way too. :o)
Let me see if I understood you.
You have, for example, the code:
<a id="previous" href="#"></a>
And by jQuery you want it to be:
<a id="previous" control="-6" href="#"></a>
Is it right?
If it is. You just have to do:
$('#previous').attr('control', -6);
If an attribute doesn't exists it's created by jQuery.
So, to remove it you can do:
$('#previous').removeAttr('control');
What you're doing doesn't respect the html rules and everything else, but it works fine, a lot of plugins do the same. ;D
I hope this could be helpful!
See you!
Try this:
$('#previous').attr('control', '-6');
Why? the $.attr(); function of jQuery allows you to add, get or update attributes (class, id, href, link, src, control and everything else!).
$("#previous").attr("control", "-6");
HTML:
<a id="previous" href="#">...</a>
jQuery:
$('#previous').attr('control', '-6');
jQuery's attr will do that. Example:
$("#previous").attr("control", "-6");
Also check out this example at http://jsfiddle.net/grfSN/.

Categories