I could be mistaken here but I thought that inline html can call an external javascript file's function with onmouseover.
For example:
<a href="#" onmouseover="updateParentImage('<?php echo $this->getGalleryUrl($_image) ?>');">
And my EXTERNAL jquery/javascript file function looks like:
function updateParentImage ($image_url)
{
alert($image_url);
$('.product-img-box .product-image img').attr('src', $image_url);
}
The function never runs. Am I completely missing something? Shouldn't that tag call the appropriate file even thought the javascript is external?
Note: If I include the javascript inline, the alert box shows but the image that I am trying to change in the document does not change, even though I"m using the same referencing as another place in the code where it successfully updates the image.
Any help would be appreciated. Thanks!
How about something like this...
<a href="#" class="imageChanger" data-imagesrc="<?php echo $this->getGalleryUrl($_image) ?>">
Then use jquery to add a mouseenter event
$(document).ready(function(){
$('.imageChanger').mouseenter(function(){
alert($image_url);
$('.product-img-box .product-image img').attr('src', $(this).data('imagesrc'));
});
});
Based on your comment, I've come to this solution that might help you:
This is one of many links
Then you can have this in your script:
(function($) {
$(document).ready(function() {
$('a').hover(function() {
// this happens onmouseenter
var imageUrl = $(this).data('imageurl');
updateParentImage(imageUrl);
}, function() {
//this happens onmouseleave
});
});
function updateParentImage(image_url) {
alert(image_url);
$('.product-img-box .product-image img').attr('src', $image_url);
}
})(jQuery);
That small piece of code binds to all 'a' elements, which might not exactly be right in your case, but it's just there as an example. Then I've wrapped all the code in a closure/immediately invoked function expression (IIFE), to make sure we don't pollute the global namespace too much. It also makes sure that $ stays jQuery inside that closure.
One more thing to be noted is that I've used the data attribute on the links to store the image URL for that link. Clean and easy :)
If you have any question, shout out!
(See comments above for context for response)
You should never have to duplicate event binding, and doing inline, obtrusive JavaScript in never an answer.
Bind once and set your URL to a property that you can grab. Further, I write the following under the assumption that you don't want to touch your external JS function:
<div id="linkContainer">
Something
</div>
JavaScript (can be placed in your page's HTML in script tags if you must):
$('#linkContainer a').bind('mouseover', function() {
updateParentImage($(this).data('imgsrc'));
return false;
});
Related
I would like to get the content of a php file on the click event of an element while blocking the ui by using this plugin. My code is this:
<li onclick="$.blockUI({ message: $.get('page.php') });" />
this does block the UI, but nothing else happens. Does the jQuery get function return the contents of that file? Should I use another function for this purpose?
What you might be looking to do would be the following:
<li onclick="javascript:showMessage();"></li>
<script type="text/javascript">
function showMessage() {
$.get('page.php', function(html) {
$.blockUI({ message: html });
});
}
</script>
Though if your page.php takes a moment or two to build, blockUI won't fire until it does.
Also, I've had mixed results with putting complex commands in an onclick or href, so I've found it more reliable to call a function.
The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.
Is it even possible to do things like this with jQuery:
I have almost empty html file index.php (with no content, only the important tags), also I have file content.php in which inside there are all the web-page content, for example this: blablabla, a lot of tags, divs and other content. For example, all this content is 700px long.
Now the thing I would like to do is with jQuery do this: in file index.php between tags input this command and after this add one more jQuery thing that puts .content.heigth() into any variable (so that it will show, how long is all the content that was in file content.php (in this example it was 700px)).
I have tried to do these things and everything goes fine until the place where I have to put into a variable that file's content length.
Here is my code. Probably someone could fix it, but in my opinion it is all wrong.
All jQuery commands are written in index.php file.
$(document).ready(function() {
$('body').append("<?php include ('content.php'); ?>");
$length = $('.content').length;
});
$length shows me 0 but it should be more than 0 ^_^
The most important thing is to know how long is the length of content in content.php file from index.php file with jQuery or any other language's help. The file including is also possible with .load('content.php') command, but this command doesn't see the included file's content length.
Thanks for help! :)
$('body').append("<?php include ('content.php'); ?>");
Don't do that! There is no good reason to do it, and most likely you'll hit a problem with line breaks and/or unescaped quotes. Just add <?php include ('content.php'); ?> directly at the end of the body, then grab the height from document.ready (you were almost there):
$(document).ready(function() {
var height = $('.content').height();
alert(height) // or do something with it
});
You mentioned .load('content.php') in the question. If the direct php include I suggested doesn't suit your needs, do something like this:
$(document).ready(function() {
// You probably want a more specific container instead of body
$(body).load('content.php', function(){
// You can only read the height inside this callback
var height = $('.content').height();
alert(height) // or do something with it
// Continue your program flow from here
// (for example, call a function)
});
// CAUTION: here the content probably didn't load yet.
// If you need to refer to it, do it from the callback above.
});
And finally: if you really get 0 for $('.content').length, that's because there is no element with class "content" in the DOM at the moment you're calling that. The length property of a jQuery object tells you how many elements match the selector you used, so zero is none.
Thanks. The problem was that I have to alert the height into (body).load code not next to that code.
Correct:
$(document).ready(function() {
$('body').load('content.php', function(){
alert($('.content').height());
});
});
Wrong:
$(document).ready(function() {
$('body').load(content.php', function(){})
alert($('.content').height());
});
From what I understand, you want the actual height (in pixels) of the content? In that case, take Malcolm's advice and use .height() instead of .length.
$(document).ready(function() {
$('body').append("<?php include ('content.php'); ?>");
$length = $('.content').length;
});
If instead you want to see how many characters are in the block, you can do something like this.
$(document).ready(function() {
$('body').append("<?php include ('content.php'); ?>");
$length = $('.content').html().length;
});
Following the example here Very Simple jQuery and PHP Ajax Request – Ready to use code
I've been successful in creating a drop down list that passes the value to an external PHP script and returns the HTML output back to a "div" on the same page and it works great.
What I want to do now is post values when I click on link instead of building a drop down list. So ...if I created this link:
Route Number 2
I want "2" passed to that external PHP script and the content changed on the " div " as it currently works with the dropdown. I don't know how to change the javascript to handle this or what "foo.php" really needs to be.
Here's the current javascript from that example:
<script type="text/javascript">
$(document).ready(function() {
$('#route_number').click(function() {
routenumber = $('#route_number').val();
$.post('api.php', { route_number : routenumber }, function(res) {
$("#mainlayer").html(res);
});
});
});
</script>
And here's what the dropdown portion of the HTML looks like:
<select name="route_number" id="route_number">
<option value="notchosen">Please Choose A Route</option>
<option value="2">Riverfront</option>
<option value="11">Magazine</option>
<option value="16">Claiborne</option>
</select>
<div id="mainlayer">
</div>
So, to be clear, instead of a dropdown that passes values, I want to create links that accomplish the same result.
Thanks in advance,
dan -
Create a class, capture its (meaning whatever link you clicked on) value, then post.
<a class="RouteNumber" href="foo.php?route_number=2">Route Number 2</a>
$(function(){
$('a.RouteNumber').on('click',function(event){
// prevent the browser's default action for clicking on a link
event.preventDefault();
// break href attribute into array, then parse desired value as int
var routenumber = $(this).attr('href').split('='),
rtnum = parseInt(routenumber[1]);
$.post('api.php',{route_number:rtnum},function(res){
$("#mainlayer").html(res);
});
});
});
If you don't need to parse the integer out of it (if a string is good enough), you don't need that second variable. You can just use routenumber[1] in the post data.
Just a heads up, I modified the jQuery to use the .on() syntax. .click() is shorthand for it, but I like using .on() just because it allows for less potential codewriting if you want to do more (like mouseenter/mouseleave, for example) because you can combine them into a single codeset.
I had hoped simply fixing #LifeInTheGrey's example would've sufficed, but there are some things I would've done differently that probably need some explaining.
Your HTML could look something like this:
<a class="route" href="foo.php?route_number=2" data-route="2">Route Number 2</a>
The JavaScript would look something like this:
$(function() {
var fill_div_with_response = function(res) {
$("#mainlayer").html(res);
};
var handle_error = function(res) {
alert('something went wrong!');
};
$(document.body).on('click', '.route', function(event) {
// prevent the browser's default action for clicking on a link
event.preventDefault();
// grab route number from data attribute
var route = $(this).data('route');
// make that post request
$.post('api.php', {route_number: route})
// handle the response
.done(fill_div_with_response)
// handle errors
.fail(handle_error);
});
});
The example uses delegated events. They're cheap to initialize and consume the least amount of memory.
The example handles errors. Most answers to questions like these neglect that. errors happen. Always. Make people aware of that. Surely throwing an alert() is not the thing you want to be doing, but it's still better than simply ignoring errors completely.
The example uses Deferreds (Promises) rather than callbacks, as this usually makes code much cleaner.
We're defining the callbacks fill_div_with_response() and handle_error() at the root closure to prevent redefining them on the next click. There's no need to feed the garbage collector.
The data attribute poses the optimal alternative to <option value="123"> in the way that it prevents you from having to parse the href attribute to extract that number from a string.
since you want to make a menu, I would modify your markup
<ul name="route_number" id="route_number">
<li value="2">Riverfront</li>
<li value="11">Magazine</li>
<li value="16">Claiborne</li>
</ul>
then simply process that list:
$('#route_number').find('li').click(function () {
var routenumber = $(this).attr('value');
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
EDIT1: As an improvement (as you seem to be pretty new to this stuff) you could use the data with altered markup as such:
<ul name="route_number" id="route_number">
<li data-routenumber="2">Riverfront</li>
<li data-routenumber="11">Magazine</li>
<li data-routenumber="16">Claiborne</li>
</ul>
Then the code would be:
$('#route_number').find('li').click(function () {// add click event manager to each li
var routenumber = $(this).data('routenumber');// get routenumber of clicked
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
Alternate code using .on() form
$('#route_number').on('click, 'li', function () {//click event manager for ul/li
var routenumber = $(this).data('routenumber');// get routenumber of clicked
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
Note that this last form binds to the #route_number element so you could add more menu options during processing and they would still work. This is also better than attachment to the document as it is a more focused approach to the event attachment.
My understanding of your question is that the functionality you have is fine, and you just need to change the look to a piece of text from a dropdown. If so, good news! You can keep (almost) the same JavaScript.
Right now, your JavaScript is getting the value of your select box, sending it via AJAX, and using the returned value. The only change you need is to get the 'value' of the text clicked.
You don't want to use a link, since that's designed to take the user someplace. Instead you can use a span and format it to look like a link, or even a button if you want that kind of look.
You will also need to change $('#route_number').val();, probably to something passed by the click event. For example:
<span id="route1" class="routeSpan" onclick="sendVal(1)">Route 1 Name</span>
<span id="route2" class="routeSpan" onclick="sendVal(2)">Route 2 Name</span>
And your JavaScript:
function sendVal(routeVal) {
$.post('api.php',{route_number:routeVal},function(res){
$("#mainlayer").html(res);
});
}
Consider the following code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
});
</script>
The first script is for background changing logic and the second script gives list of thumbnails of the themes. The problem is that the first script doesn't work beacause of the second. If I don't use this AJAX technique everything works fine. Working code:
<script src="js/backgroundChanger.js" type="text/javascript"></script>
<div id="dcontent">
<?php include('printThumbs.php'); printThemesThumbs();?>
</div>
The background changing logic looks like:
$(function() {
$('.themes li a img').click(function() {//code
});
Any help will be greatly appreciated.
in your first snippet of the code you defined a click function on .Theme and in the third snippet of the code .theme, is this correct?, i mean both classes seems to be different try to use the same class name return by your php function.
You're calling $(document).ready() twice, as $() is an alias, and the second definition is overwriting the first. First you are setting the document ready callback to
function() {
$('.themes li a img').click(function() {//code
}
and then overwriting it with
function() {
$('.Themes').click(function(){
$('#dcontent').load('printThumbs.php');
});
}
you have to add your second code in a callback function. you can't bind something if it is not already in the dom. if you want to make changes to the printThumbs output you need to add a callback...
<script>
$(document).ready(function() {//this is also a callback function when document is ready
$('.Themes').click(function(){//this can be understand as a call back too... code is fired after a click
$('#dcontent').load('printThumbs.php',function(){/*your callback code here...this code will be fired after you've loaded printThumbs*/}
});
});
</script>
if you want to do some jquery or other client side stuff on the respons of an ajax call (html,xml, json or whatever) you have to specify a callback function. to make things less complicated you have to look at the callback function just as the on document ready function with the difference that the callback is applied to the respons of your ajax call. if the code is not in a callback function you can't manipulate the respons because it is not injected in the dom/it simply does not exists in your browser when the document is ready.