Javascript code to Jquery code not working - javascript

I have an image that is changed when I click on several links. The following javascript code works well :
<img src="myImage.png" id="mainImg" />
Report1
Report2
But I'm trying to change the code to use Jquery code instead. It calls the same server code as the javascript example. No errors are generated & a png is streamed back. But the image is not updated on the html page. To make things worst, the html moves to the top of the page. In the working javascript code, the image would fresh with a nice ajaxy feel where only the image would change & the rest of the page would not move. My Jquery code is below :
<img src="myImage.png" id="mainImg" />
Report1
Report2
<script type="text/javascript">
$(document).ready(function(e) {
$("#report1_id").click(function(e) {
alert("This Is Report1");
d = new Date();
$("#mainImg").attr("src", "http://localhost/convertToReport1.do?"+d.getTime());
});
$("#report2_id").click(function(e) {
alert("This Is Report2");
d = new Date();
$("#mainImg").attr("src", "http://localhost/convertToReport2.do?"+d.getTime());
});
});
</script>
Can anyone see what I'm doing wrong? Any help would be appreciated.

From your code, the image src should change, but maybe it doesn't change to what you'd like. Make sure that http://localhost/convertToReport1.do returns exactly what you need (ideally, you can specify that in the question itself).
The page jump happens because of the anchors href attribute. Either remove it, or prevent the default anchor behaviour in your click handler function, like this:
$("#report1_id").click(function(e) {
e.preventDefault(); // <--- this is the key, return false would also work at the end
alert("This Is Report1");
d = new Date();
$("#mainImg").attr("src", "http://localhost/convertToReport1.do?"+d.getTime());
});
See it in action here: http://jsfiddle.net/egvac61c/

Related

Track JavaScript event

I have GA on my website and i'm trying to track every click on the website. The following JavaScript must be used, it acts like an overlay on the page:
<script type="text/javascript">
var tile = new HTMLLiveTile.TileController();
window.onmousedown = function() {
tile.openStoreProduct("var1", "var2", "var3");
}
</script>
What would be the HTML equivalent code to track this?
Right now i have:
<a id="tile" onClick="ga('send', 'event', 'click1', 'click2', 'sample');"><img src="./images/image.png"> </a>
I'm very new to this, sorry if it's redundant. My assumption was to track the variable and add it to the onClick.
I guess you are asking for a solution that does not require much hassle and much changing in code and moreover without any need to change your previous code.
you can use event.target.+ things you need to know to get info.
function mouseTrack(){
var element_name = event.target.tagName;
alert("mouse click was detecteted at: "+ element_name);
}
window.addEventListener('click', mouseTrack(), false);
this code will alert the Tag Name of Element clicked (like DIV, a, SPAN etc you know the list.). But this code is awful.It wont work in Mozilla FF, It wont work In IE 9 below. I took some time to create a fiddle on JSFiddle.net you can view example I made Here

shorthand for .load() ajax links with loader

here's the structure of the code: http://jsfiddle.net/ss1ef7sq/
although it's not really working at js fiddle but the code itself is working as i've tested it locally through firefox.
this is where i've based this on: http://html.net/tutorials/javascript/lesson21.php
jquery/ajax:
$('#ep-101').click(function(){$('.main-container').load('link.html #ep101').hide().fadeIn(800);});
$('#ep-102').click(function(){$('.main-container').load('link.html #ep102').hide().fadeIn(800);});
$('#ep-103').click(function(){$('.main-container').load('link.html #ep103').hide().fadeIn(800);});
$('#ep-104').click(function(){$('.main-container').load('link.html #ep104').hide().fadeIn(800);});
$('#ep-105').click(function(){$('.main-container').load('link.html #ep105').hide().fadeIn(800);});
so my question is, is there a way to make it like a shorter code where it can just get the value of those #10ns or assuming that there will be a different page with it's own nest of unique ids without typing them individually? there's still a lot i don't understand with ajax so i'd appreciate it if anyone can help & explain at least the gist of it as well.
i've looked around online but i'm really stuck. i also at least found out that it's possible to add transitions but the way it's coded there is that it will only have the transition for the incoming page & not the one that will be replaced. i also have a prob with page loaders effects but i'll save it for when i'm stuck there as well.
thanks in advance. =)
Use classes instead of id's. Set href attribute which you want to load on click and access it via $(this).attr('href').
<a class="load-me" href="link1.html">link 1</a>
<a class="load-me" href="link2.html">link 2</a>
...
Script:
$('.load-me').click(function(e){
e.preventDefault();
$('.main-container').hide().load($(this).attr('href'), function() {
// ...
$(this).fadeIn(800);
})
});
JSFiddle
If you need the load to wait container hiding animation, you could make it other way.
$('.load-me').click(function(e){
e.preventDefault();
// get the url from clicked anchor tag
var url = $(this).attr('href');
// fade out the container and wait for animation complete
$('.main-container').fadeOut(200, /* animation complete callback: */ function(){
// container is hidden, load content:
$(this).load(url, /* load complete callback: */ function() {
// content is loaded, show container up
$(this).slideDown(200);
});
});
});
JSFiddle

jquery load image to div after clicking href

I know this has been asked many times here, actually I found plenty of questions, each of them with a very good answer, I also followed those answers, used the different ways I found but I still don't get it to work.
What I'm trying to do is to load an image into a div, after clicking a link, instead of redirecting to a new page.
I'm using Pure Css (http://purecss.io/) to create a menu, the menu is made of a list, and each list item has a link inside it, like so:
<div class="pure-menu pure-menu-open" id="vertical-menu">
<a class="pure-menu-heading">Models</a>
<ul id="std-menu-items">
<li class="pure-menu-heading cat">Menu heading</li>
<li>Model 1</li>
</ul>
</div>
In that same html file, I have another div where I want to load the image:
<div id="model-map"></div>
I've tried the following ways, using jquery, in a separate js file:
I followed the selected answer for this question, which seemed to have the best approach (Can I get the image and load via ajax into div)
$(document).ready(function(){
console.log("ready"); //this shows on console
$('.model-selection').click(function () {
console.log("clicked"); //this doesn't show after clicking
var url = $(this).attr('href'),
image = new Image();
image.src = url;
image.onload = function () {
$('#model-map').empty().append(image);
};
image.onerror = function () {
$('#model-map').empty().html('That image is not available.');
}
$('#model-map').empty().html('Loading...');
return false;
});
});
As you see, the console.log("clicked") never executes, I'll be ashamed if it's something stupid, cause it seems that the function is not handling the click event properly.
I get the image of course, but in a new page (default behavior of clicking the href) and I want it to load on the div without being redirected. I hope you can help me.
Thanks in advance!
Edit
The code above is working, and both answers are correct, the issue was due to some code inside tags in my html ( YUI code to create the dropdowns for the menu) and it was conflicting with my js file. I moved it to the actual js file and now it works as expected.
Thanks!
You need to use event.stopPropagation();
$('.model-selection').click(function( event ) {
event.stopPropagation();
// add your code here
});
You just need to prevent the default behavior of moving to a new page for <a> tags, to do this say e.preventDefault() first:
...
$('.model-selection').click(function (e) {
e.preventDefault(); // Stops the redirect
console.log("clicked"); // Now this works
...
)};
...

HTML Source Editor - Web Part

I am working on an HTML web part. I wanted to make other web parts on the page to be collapsable and expandable. I found this script to place in an HTML form web part. It does exactly what I want. The only thing is all the other parts automatically are expanded when the page is loaded. I read through the script but, I am not familiar with jQuery syntax. The line in the code that I believe I need to change to make the sections automatically collapsed is:
$(this).closest('.s4-wpTopTable').find('tr:first').next().toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src',Expand );
I believe I just need to change where it has toggle as visible to is not visible. I am not sure how to write that.
Here's the whole script:
<script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('.s4-wpTopTable').find('tr:first h3').append('<a class=\'min\'
style=\'float:right\'><img src=\'/_layouts/images/collapse.gif\'/></a>');
var Collapse = "/_layouts/images/collapse.gif";
var Expand = "/_layouts/images/expand.gif";
$('.min').click(function(){
var img = $(this).children();
$(this).closest('.s4-wpTopTable').find('tr:first').next().toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src',Expand ); }); }); </script>
Here is trick may be it will work for you.Click on Edit Web part,Under Appearance find the chrome state, you need to set Chrome state to 'minimized',By default Chrome state will be 'Normal.
Then place your code either in CEWP or in your .aspx page using Sharepoint Designer.

Same JQuery click function for numerous links

I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>

Categories

Resources