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)" />
Related
I have the following code
http://jsfiddle.net/6xcn6gzj/, I need to remove an element off the page using its attribute, so I opted for jQuery's remove. My problem is that once I click on the image, nothing happens. I tried calling the function from javascript itself and it was working perfectly. For some reason, the event is just not happening.
HTML:
<div>
<img src="whatever" alt="test" onclick="close('test')">
</div>
Javascript:
console.log('hi');
function close(template) {
console.log(template);
$('body').find('img[alt="'+template+'"]').remove();
}
The console is logging "hi" which indicates that javascript is running fine but it never logs the template name. Any help is appreciated.
Two problems:
Don't name your function close, that will conflict with window.close
Your fiddle was set to load your code in the onload handler, so your function was local to that function. Change your fiddle to load the script in the <head> http://jsfiddle.net/6xcn6gzj/7/
function doClose(template) {
console.log(template);
$('body').find('img[alt="' + template + '"]').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="whatever" alt="test" onclick="doClose('test')" />
</div>
Maybe you should just call this.remove()?
<div>
<img src="whatever" alt="test" onclick="this.remove()">
</div>
http://jsfiddle.net/6xcn6gzj/2/
I have this code for a small jQuery game I'm making, and all the pictures (characters) are hidden by default. There's a question that says "Are you ready to play?" and a yes or no button. When you click the yes button, it hides the buttons and the text. It is also supposed to display the first image, which is #main. For some reason, it's not working.
Here's the jQuery code with the images under:
$(document).ready(function(){
$('#main,#batman,#car,#hobo,#knife,#gangfight,#ganggun,#gangknife,#blood').hide(-100);
var main=$('#main');
batman=$('#batman');
car=$('#car');
hobo=$('#hobo');
cop=$('#cop');
knife=$('#knife');
gangfight=$('#gangfight');
ganggun=$('#ganggun');
gangknife=$('#gangknife');
blood=$('#blood');
document.write('<title>LOAUP</title>');
document.write('<center><h1>The life of an unlucky person</h1></center>');
document.write('<center id="start">Are you ready to play?</center>');
document.write('<center><button id="yes">Yes</button><button id="no">No</button></center>');
$('#yes').click(function(){
$('#yes,#no').hide(function(){
$('#start').hide();
$('#main').show
});
});
$('#no').click(function(){
$('#yes,#no').hide();
$('#start').hide();
document.write('<center>Ok, come back another time then.</center>');
});
});
//Images below this (HTML)
<img id='main' src='/jquery/sprites/spritePerson.png' />
<img id='batman' src='/jquery/sprites/spriteBatman.png' />
<img id='car' src='/jquery/sprites/spriteCar.png' />
<img id='hobo' src='/jquery/sprites/spriteHobo.png' />
<img id='cop' src='/jquery/sprites/spriteCop.png' />
<img id='knife' src='/jquery/sprites/spriteKnife.png' />
<img id='gangfight' src='/jquery/sprites/spriteGangFight.png' />
<img id='ganggun' src='/jquery/sprites/spriteGangGun.png' />
<img id='gangknife' src='/jquery/sprites/spriteGangKnife.png' />
<img id='blood' src='/jquery/sprites/spriteBloodPuddle.png' />
Edit:
Here's the example:
http://jsbin.com/ocowas/1
In your #main click function change
$('#main').show
to
$('#main').show();
Your variable list should be comma seperated not colon seperated. and you may also want to rename your variables to make them more obvious and easier to read/remember by prefixing with a $ sign. For example when you store a selector as a variable use
var $element = $('#element'),
$element2 = $('#element2'),
$element23 = $('#element23');
Further, the hide() function does not take negative numbers as you have used. Just use hide() for an instant hide, or hide(100) for fast, hide(2000) for slow.. check: http://docs.jquery.com/Effects/hide
To append html to your document without using document.write, you can store the html as a variable, then select the body tag, or any other tag and append/prepend or replace the html to that, for example.
$('body').append(yourHTMLvar);
$('body').prepend(yourHTMLvar);
$('body').html(yourHTMLvar);
The 'title' tag should only appear between the 'head' tags of your html document. Use a heading tag instead, 'h1' to 'h6'.
The html 'center' tag is also deprecated as far as I know. Try using 'span', 'p' or even 'div' instead.
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.
I was looking over the WebGoat exercises, and for one question they ask that you create a JavaScript alert using an img tag.
Their solution is thus:
<img src=x onerror=;;alert('XSS') />
Looking at their solution, I wonder why two (as opposed to just one) semicolns are necessary before the actual alert?
Indeed the semicolons aren't necessary i just tested the same tag w/o the semicolons on FF5 and Chrome latest, they both send the alerts with this
<img src=x onerror=;;alert('XSS') />
<img src=x onerror=alert('XSS') />
<img src="x" onerror="alert('XSS')" />
i think they are trying to stop the onerror event in the first semicolon, then output the bogus code out of the event in the alert
i tried this
<img src=x onerror=alert('eventfire');;alert('XSS') />
and it encloses both alerts inside the event, so its not running the second alert outside the event scope.
answer? seems to be doing the same thing w/o the semicolons (maybe there for old browsers that parse the html poorly and execute the alert outside the scope of the event???)
i have jquery, but it is not going to next page, it always display images and waits, never proceed to next page.
HTML code:
<div id="toHide" class="pb-text-align-center">
<img style="display: inline" src="img/load.gif" />
<form wicket:id="safeForm" class="clearfix">
<input type="hidden" wicket:id="submitted" value="false" />
</form>
</div>
HTML view source:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
$('.toHide').show().doTimeout(100,function() {
$('.toHide').find('safeForma3').submit();});
</SCRIPT>
wicket code:
static private class SafeSubmitBehaviour extends AbstractBehavior{
public void onRendered( Component component ) {
super.onRendered( component );
StringBuffer buffer = new StringBuffer(200);
buffer.append("<script type=\"text/javascript\" >\n");
buffer.append("var $ = jQuery.noConflict();\n ");
buffer.append(" $('.toHide').show().doTimeout(100,function() { $('.toHide').find('");
buffer.append(component.getMarkupId()).append("').submit();});\n</script>");
component.getResponse().write(buffer);
}
}
buffer.append(component.getMarkupId()).append("').submit();});\n</script>");
i have tried with: $('.toHide').find('form').submit();});. But still no use.
After chaging $('.toHide') to $('#toHide'), page is going ot next page, but animation is not happening in IE6/7, it works fine in FF.
The "toHide" <div> has that string as it's id value, not it's class, so you need:
$('#toHide')
The selector ".toHide" looks for an element with "toHide" as part of the class, so that wouldn't find your <div> at all.
To find the form, you'd use
$('#toHide form').submit();
I think you should try this:
$('#toHide').find('form').submit();
Or if the form has an ID on it (I'm not familiar with Wicket) you can just use:
$('#safeForm').submit();
The ID selector uses a '#' charactor, not a '.', which is the class selector prefix.
There is no id named 'safeForm15' in your HTML, which is what your setTimeout is trying to select. In fact, the form has ID namespaced, which I believe is illegal to begin with.
Regardless, the quick fix is to cue off of 'toHide', and get rid of the component.getMarkupId bit.
$('#toHide').find('form').submit();
Added:
You need to change this:
buffer.append(" setTimeout(function(){ $(\"#").append(component.getMarkupId()).append("\").submit()}, 100);\n");
to this:
buffer.append(" setTimeout(function(){$('#toHide').find('form').submit();}, 100);\n");
This is a problem with IE, if you have a GIF that is not visible and then set it to visible the animation doesn't work.
Best thing to do is just used an empty image tag like this <img src='' /> and then when you want it to become visible set the src to the correct path i.e. <img src='AnimatingImg.gif' />.
It should work if you do it this way.
EDIT
You can do it like this:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
$('#toHide').show();
$('#loadingImg').attr('src', 'img/load.gif');
setTimeout(function() {
$('#toHide').find('safeForma3').submit();
}, 100);
</SCRIPT>
html code:
<div id="toHide" class="pb-text-align-center">
<img id="loadingImg" style="display:inline" src="" />
<form wicket:id="safeForm" class="clearfix">
<input type="hidden" wicket:id="submitted" value="false" />
</form>
</div>
Try that, might want a bit of fiddling though.
Others have mentioned the problem with your selector.
However, this code also appears naked between two script tags. This means that they will be executed as soon as they are parsed. This means that they could be executed before the whole DOM is loaded, rendering them ineffective.
You need to use something like this:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
$(document).ready(function(){
$('#toHide').show().doTimeout(100,function() {
$('#safeForma3').submit();
});
});
</SCRIPT>