Grails: JS function to change src of img is not responding - javascript

I am trying to change the src of an img under a certain condition. I know the condition returns true appropriately, because I previously wrote in an alert(). For some reason, the function is not changing the src of the img and dynamically updating the page. Could this have anything to do with the fact that I am using the jquery library? I would think you can still use the stand js syntax. Here are my code snippets and the corresponding source code from google chrome.
.gsp:
<script type="text/javascript">
function onSuccess(data){
if(data.hasHearted){
document.getElementById("changer${user.id}").src = "${resource(dir: "images/images", file: "heart_red.png")}";
}
}
<figcaption id="secondcap" onClick="${remoteFunction(controller:'user', action:'heart', onSuccess: 'onSuccess(data)', params:[userID:user.id])}">
<img id="changer${user.id}" src="${resource(dir: "images/images", file: "heart.png")}" alt="heart">
</figcaption>
Chrome source (I've omitted some things for privacy):
<script type="text/javascript">
function onSuccess(data){
if(data.hasHearted){
$('#changer3').attr('src','/Personably/static/images/images/heart_red.png');
}
}
</script>
<div class="persons">
<figure class="user_image">
<img class="user_profile_pic" src="omitted for privacy..." onmouseover="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/hasHearted',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});"/>
<figcaption id="firstcap">
Omitted for privacy...
</figcaption>
<figcaption id="secondcap" onClick="jQuery.ajax({type:'POST',data:{'userID': '3'}, url:'/Personably/user/heart',success:function(data,textStatus){onSuccess(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});">
<img id="changer3" src="/Personably/static/images/images/heart.png" alt="heart">
</figcaption>
</figure>
</div>

Since you are using jquery, have you tried using the jquery id selector $(“#id”) and/or the jquery .attr function?
http://api.jquery.com/id-selector/
http://api.jquery.com/attr/#attr2

I'm not sure that changing the src attribute after the page is loaded will change what the user sees, even if it changes the code, because the document is already loaded.
Instead, you should probably put both images (heart.png and heart_red.png) on the page, and then hide/unhide them with styles depending on the output of your controller action. The jquery .toggle(Boolean) method can be very useful for stuff like this. http://api.jquery.com/toggle/
Inside your JavaScript function, you could just have something like:
$('#heart3').toggle(!data.hearted);
$('#heart_red3').toggle(data.hearted);
Then, when data.hearted is true, red heart will show, and plain heart will hide.

Related

How I can create a button for save a image with Javascript or any Javascript framework?

I would like save with a button a generated picture. I see the fastest solution is JavaScript, probably JQuery or any framework.
My application generate a img label, for example:
<img src = "data:image/png;base64,iVBORw0KGgo...(it's very long)"/>
The many problem is the src attribute because change for my application, first I need catch the URL of this.
Thank you very much!
You can use the download attribute in HTML. If the img src is automatically generated, you could use the script below to put it in the href:
$('#save').prop('href', $('img').prop('src'));
<img src="http://blog.grio.com/wp-content/uploads/2012/09/stackoverflow.png"/><br/>
<a id='save' download>Save</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

JavaScript "<SCRIPT>" in Image src attribute

So I have the following JavaScript function.
var LogoUrl = function() {
document.write('views/img/common/site-logo.svg');
}
And I want to have this function used in a html img src attribute.
Here is a example though this syntax wouldn't work, it should give you an idea of what I am looking for.
<img class="site-logo" src="<script> LogoUrl() </script>" alt="Site Logo">
And hoping this would export the following in the browser
<img class="site-logo" src="views/img/common/site-logo.svg" alt="Site Logo">
What is the best approach to doing this?
You can do this with the following instead:
<script>
document.write('<img class="site-logo" src="' + 'views/img/common/site-logo.svg' + '" alt="Site Logo">');
</script>
Since the script tag is indeed a tag, you can't put it inside the attributes of another tag.
A much better approach however would be the following:
Prepare a span element for the element to appear in, and give it a specific id. This would be your HTML:
This is my image: <span id="myImg"></span>.
and this will be your jQuery code:
$(function() {
$('<img>').class('site-logo')
.attr('src', 'views/img/common/site-logo.svg')
.attr('alt', 'Site Logo')
.appendTo('#myImg');
});
Alternatively, instead of preparing a span, you could prepare the image without defining a src attribute, with the following HTML:
This is my image: <img id="myImg" class="site-logo" alt="Site Logo">.
and the following jQuery code:
$(function() {
$('#myImg').attr('src', 'views/img/common/site-logo.svg');
});
You can use jquery $(document).ready() to set the image src.
$(document).ready(function (){
$('img.site-logo').attr('src', 'views/img/common/site-logo.svg');
});
You could do this - but this makes it obstructive.
<script>document.write("<img class=\"site-logo\" src=\"views/img/common/site-logo.svg\" alt=\"Site Logo\">")</script>
It is also not very organised because it ties everything so much with the markup that you might as well just have it as markup.
You're better off doing it properly by changing the src property
var logo = document.getElementsByClassName('site-logo')[0];
logo.src = 'http://www.develop.com/Images/v3/tech-symbols/angularjs_logo.png';
demo here http://jsfiddle.net/andyw_/XxTuA/268/
If this is all you need to do - I don't think it justifies the use of a selector library or front-end framework.

javascript change Image by clicking thumbnail

I am a newbie in javascript and tried a lot of things for hours, but nothing worked.
I will change a big imgage by clicking on a thumbnail.
Untill now I got following script. Not much really... :-(
<script type="text/javascript">
function changeImage() {
document.getElementById("img").src="img/upload/test1.jpg";
}
</script>
<img id="img" name="change" src="img/upload/test.jpg">
<img src="img/thumbnail/test.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
<img src="img/thumbnail/test1.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
All big picture are under src"img/upload/xxx.jpg" and all thumbnails under src="img/thumbnail/xxx.jpg". When I click the thumbnail, it have to change the big picture and it have to give the parameter in the javascript. Like onclick="changeImage(xxx.jpg).
The problem is every page have other pictures. I get them from a database. So the name of the picture is like a variable. I hope you understand. It is hard for me to explain. :-(
Thanks for your help in advance.
Greets Yanick
Pass the image parameter to the function like,
function changeImage(image) {
document.getElementById("img").src=image;
}
<img src="img/thumbnail/test.jpg" alt="" id="img"
onclick="changeImage('img/upload/test1.jpg')" />
Keep ids unique. DOM elements "must" possess unique IDs for all practical reasons.
Though you could do an inline onclick, a better way to proceed with it is something as follows.
Assuming you have the images generated from some templating library either on the client or from the server, add data attributes with the image sources and a common class to all of these elements right there and add an event listener from your Javascript bound to elements matching the class and picking up the data attribute to replace the image source.

Fancybox 2.1.3 indirectly called from iframe returns 'The requested content cannot be loaded. Please try again later.'

I am struggling with setting up the latest fancybox. I manage to call fancybox from an iframe to open on the main-page, but it does not seem to find the content.
So, I have the following setup:
main-page:
Opens iframes and contains javascript functions to display an image in the fancybox.
For testing purposes I do not call the function with any arguments yet and I use hardcoded images, till I get it working. So the javascript functions looks like this:
$jj = jQuery.noConflict();
function triggerFancybox(){
$jj(".triggerid").trigger("click");
alert("Fancybox triggered!");}
function callMe(){
$jj(".triggerid").fancybox('images/showroom/playground/displaced/dispm_6.jpg' , {'type' : 'image'});
triggerFancybox();}
function callMe1(){
$jj(".triggerid").fancybox('http://demo.artonbit.com/images/showroom/playground/displaced/dispm_6.jpg' , {'type' : 'image'});
triggerFancybox();}
function callMe2(){
$jj(".triggerid").fancybox('http://demo.artonbit.com/images/showroom/playground/displaced/dispm_6.jpg');
triggerFancybox();}
The main-page also contains a dummy element, which I use to open the fancybox content:
<!-- This id can be called by an iframe for the fancybox>
iframe:
The iframe currently only contains an onclick trigger, here are the latest attempts:
<p><a class="fancyframe" rel="group" href="images/showroom/playground/displaced/dispm_6.jpg" onclick="parent.callMe();return false;"><img style="float: left;" alt="PXM Commercial Shot1" src="images/showroom/playground/displaced/dispm_6.jpg" height="135" width="240" /> </a>
</p>
<p><a class="fancyframe" rel="group" href="images/showroom/playground/displaced/Disp_7b1.jpg" onclick="parent.callMe1();return false;"><img style="float: left;" alt="PXM Commercial Shot1" src="images/showroom/playground/displaced/dispm_6.jpg" height="135" width="240" /> </a>
</p>
<p><a class="fancyframe" rel="group" href="images/showroom/playground/displaced/dispm_9.jpg" onclick="parent.callMe2();return false;"><img style="float: left;" alt="PXM Commercial Shot1" src="images/showroom/playground/displaced/dispm_6.jpg" height="135" width="240" /> </a>
</p>
<p>Another Test
So, the fancybox gets triggered, but it can't find the content. I tried many different ways of calling fancybox, but I always end up with the error message from the title.
The image references are correct. All the libraries necessary, should be included. I tested this with an id as target and currently I am using a class (as somewhere suggested in the Fancybox FAQ).
What do I miss?
I first implemented this with the older fancybox 1.3.4, which worked fine.
You can find a running demo of the problem at this address:
http://demo.artonbit.com
Once you are on the front-page, just click the most top-left tile (Displaced!), which will open an iframe containing some text and three thumbnails. These are the triggers for the fancybox. They succesfully call the "callMe" methods, but then fancybox fails to find the content.
First thing I checked was your site and the scripts you loaded, so I think that you only need a single instance of jQuery rather than complicate yourself with two different versions and namespaces ..... anyway.
Now your code, it doesn't have the proper format because you either :
1) Bind fancybox to a selector (a class for instance) like :
$(".selector").fancybox({
// API options
});
2) Call fancybox manually
$.fancybox([
href: 'images/showroom/playground/displaced/dispm_6.jpg'
],{
// API options
type: "image"
});
... but not :
$(".triggerid").fancybox('images/showroom/playground/displaced/dispm_6.jpg', {
// API options
'type' : 'image'
});
... which is a mix of the two above.
In your particular case, you just need to change inside your functions the fancybox script to the proper format like :
function callMe(){
$(".triggerid").fancybox({
href: 'http://demo.artonbit.com/images/showroom/playground/displaced/dispm_6.jpg'
});
triggerFancybox();
}
... or use your namespace $jj
NOTE : since the href has an image extension you don't actually need to specify type: "image"
Seeing is believing ...JSFIDDLE

Inline event handlers and anonymous functions

I have a need to dynamically include and run a script in a page. I am using an image onload event for this:
<img src="blank.gif" onload="DoIt" />
The DoIt function looks like this (just made up this example):
this.onload=' ';this.src='image.jpg';
I have no control on the page itself (I only control the HTML string that the page will call), so I need to include the DoIt function explicitly in the markup.
I tried using an anonymous function, but it didn't work:
<img src="blank.gif" onload="function(){this.onload=' ';this.src='image.jpg';}" />
Should I just write the script inline, like this:
<img src="blank.gif" onload="this.onload=' ';this.src='image.jpg';" />
And in this case are there any limitations (e.g. script length)?
Thanks for your help!
The this won't work inside the function since the function is called by the window object, therefore the this will refer to window.
If you want to wrap your code inside a function you must wrap that function, call it with the this set to the element or pass the this as a parameter:
<html>
<body>
<!-- call the function and set the this accordingly-->
<img src="foo.png" onload="(function(){...}).call(this)" />
<!-- pass the this as a parameter -->
<img src="foo.png" onload="(function(e){....})(this)" />
</body>
</html>
Yet this doesn't really make sense to me:
I have no control on the page itself (I only control the HTML string that the page will call),
Do you only have control over the img tags? If you can output abritary HTML, then why not just put something in a `script' tag?
Update
With a script block you could declare your function in there and then simply call it in the onload event.
<script>
function doIt(el) {
// code in here
console.log(el.id); // you could do stuff depending on the id
}
</script>
<img id="img1" src="foo.png" onload="doIt(this)" />
<img id="img2" src="foo.png" onload="doIt(this)" />
Now you need only one function for many images.
And if you need to get really fancy, you can setup your script tag to pull in jQuery or any other library.
<script src="somepathtojquery"></script>
<script>
// do jquery stuff in herep
If you need a lot of these handlers jQuery could do the job.
Still I'm asking my self when you have full control over the HTML why don't you use a library in the first place? :)
Try:
<img src="blank.gif" onload="(function(el){el.onload=' ';el.src='image.jpg';})(this)" />

Categories