jQuery- Inserting GET data into div only works after second trigger - javascript

I am trying to use jQuery to fetch data and place it into a div after I hover over a link. It is working, but only on the second hover. The first hover instance does not do anything. Why?
jQuery(document).ready(function($){
$(".tiptrigger").hover(function() {
var s_href = $(this).attr('href');
var s_title = $(this).attr('title');
$(".tiptitle").empty().append(s_title); // Only working after second instance
var get_url = "/root/data.php"+s_href;
$.get( get_url, function( data ) {
var tip_content = data;
$("#tipcontent").empty().append(tip_content); // Only working after second instance
});
});
And the HTML:
<a class="tiptrigger" title="My Title" href="?s=something">Hover over me</a>
<div class="tipbox"><p class="tiptitle"></p><p id="tipcontent"></p></div>
And lastly, the PHP page that the GET request is being sent to:
<?php
if ($_GET['s'] == "something") {
echo "This should appear in the paragraph.";
}
?>
What am I doing wrong here?

Provide an empty stub function for the handlerOut() second handler of .hover(), you are just providing one handler, which is executed both when going over and out of the link, so do it like this:
$(".tiptrigger").hover(function() {
var s_href = $(this).attr('href');
var s_title = $(this).attr('title');
$(".tiptitle").empty().append(s_title); // Only working after second instance
var get_url = "/root/data.php"+s_href;
$.get( get_url, function( data ) {
var tip_content = data;
$("#tipcontent").empty().append(tip_content); // Only working after second instance
}
, function() {}); //PROVIDE EMPTY HANDLER FOR MOUSEOUT

Related

Change value of <p> in PartialView

I have PartialView with <p>
Here is code
<p id="findings-date" class="blue-text">Test</p>
I load partialView into div via this js code
$(document).on('click',
'.findingval',
function () {
var findingval = $(this).text();
var idvalue = $(this).siblings('.idvalue').text();
$('#left-window').load('#Url.Action("Findings", "PatientDatabase")');
});
I need to change value of p to findingval
I tried
$('#findings-date').text(findingval); but it not works.
After this I tried just to get value like this $('#findings-date').text();
But it's null. Why so?
Seems it try to get data when partialView not appended.
Full code of script
$(document).on('click',
'.findingval',
function () {
var findingval = $(this).text();
var idvalue = $(this).siblings('.idvalue').text();
$('#left-window').load('#Url.Action("Findings", "PatientDatabase")');
var date = $('#findings-date').text();
alert(date);
});
load() is asynchronous. Use the complete callback so the new html is loaded before you try to access it
$('#left-window').load('#Url.Action("Findings", "PatientDatabase")', function(){
// new html exists now
$('#findings-date').text(findingval );
});

Bind bxslider after ajax call in WP

Please help me with binding bxSlider on Ajax response, tried on. , tries function after but no help (think problem with lack of JS syntax knowledge).
Here's JS:
$('.catalog-menu-links a').click(function(event) {
event.preventDefault();
// Set class to newly selected language button
$('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
$(this).parent().addClass('current-menu-item');
// Get new language data URL
var href = $(this).attr("href");
$.get(href, function(data) {
var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
$('.catalog-slider').fadeOut('slow', function(){
$('.catalog-slider').html(ajaxCatalogSliderContent);
}).fadeIn();
//alert($('.catalog-slider').html());
$('body .bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});
});
});
I tried this:
function startCatalogSlider() {
$('.bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});}
startCatalogSlider();
$('.catalog-menu-links a').click(function(event) {
event.preventDefault();
// Set class to newly selected language button
$('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
$(this).parent().addClass('current-menu-item');
// Get new language data URL
var href = $(this).attr("href");
$.get(href, function(data) {
var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
$('.catalog-slider').fadeOut('slow', function(){
$('.catalog-slider').html(ajaxCatalogSliderContent);
}).fadeIn();
//alert($('.catalog-slider').html());
startCatalogSlider();
});
});
But with no successful result

Knockout.js: Click binding only working first time I click?

Having some issues with a function in Knockout.js. Basically it is a menu where the first menu item "Översikt" should fetch a JSON array and populate the view.
The knockout code:
self.ongoingAuctions = ko.observableArray([]);
self.getOngoingAuctions = function(data) {
$.getJSON("assets/json/auctions.json", function(data) {
self.ongoingAuctions(data);
});
}
My click binding:
The problem is that this only works the first time I click on the menu item. The JSON doesn't get fetched the second, third, n:th time.
What am I doing wrong? Or have I misunderstood something?
Thanks in advance!
I have shared this fiddle for you that shows something else is wrong in your code that you havent not specified in the question:
It makes the call to the non existing json (in my case) every time you click
JS Fiddle to working code
var viewModel = function(){
var self = this;
self.ongoingAuctions = ko.observableArray([]);
self.getOngoingAuctions = function(data) {
$.getJSON("assets/json/auctions.json", function(data) {
self.ongoingAuctions(data);
});
}
self.setHeadline = function(){
console.log('set headline')
}
self.headline = function(){
console.log('headline');
}
}
var myVm = new viewModel();
ko.applyBindings(myVm);

Redirect links on a webpage to a javascript function

I am trying to redirect links on a web page and in this simple example, it just goes through a simple check for a cookie to be set.
Not sure if that's the right way to take care of this situation in the first place, and if I am going to run into problem when there are several links with the "download_link" class, but even right now, with only one of such link, the destination is set to undefined, it looks like the $(this) in the call to redirector is actually pointing the the whole HTML document instead of just the element I am trying to change...
function redirect_link(e, destination) {
if ($.cookie("contact_set") == "true") {
window.location.href = destination;
} else {
alert("cookie not set");
}
}
function redirector(destination) {
alert("creating redirector to "+destination);
return function(e) {redirect_link(e, destination)};
}
$(document).ready(function() {
$('.download_link').click(redirector($(this).attr("href")));
$('.download_link').attr("href", "#");
});
You're accessing $(this) from the scope of document's ready callback, so $this points to a HTMLDocument object!
$(document).ready(function() {
var $downloadLnk = $('.download_link');
$downloadLnk.click(redirector($downloadLnk.attr("href")));
$downloadLnk.attr("href", "#");
});
As you requested it in your comment:
$(document).ready(function() {
$('.download_link').each(function() {
var $lnk = $(this);
$lnk.click(redirector($lnk.attr("href")));
$lnk.attr("href", "#");
});
});
$(function() { // <-- Short for $(document).ready(function() {
$('.download_link').each(function() {
var $this = $(this);
$this.click(redirector($this.attr("href"));
$this.attr("href", "#");
});
});
You can always use the target :
$(document).ready(function() {
$('.download_link').on('click', redirector); //bind to function
$('.download_link').attr("href", "#");
});​
function redirector(event) {
alert("creating redirector to "+event.target.href); //event.target
return function(e) {redirect_link(e, destination)};
}
But by the time your link is clicked the href will be # no matter what you use, as you set it to that value on the next line after the click handler ?

Why does my jQuery event handler fail when attached to multiple elements?

I am using jquery to add mulitple new "addTask" form elements to a "ul" on the page every time a link is clicked.
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
saveTask();
});
These new nested ul elements all have an button with the same class "saveTask". I then have a function that allows you to save a task by clicking on an button with the class "saveTask".
// Save New Task Item
function saveTask() {
$('.saveTask').click(function() {
$this = $(this);
var thisParent = $this.parent().parent()
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
}
This essentially allows the user to enter some text into a form input, hit save, and then the task gets saved into the database using ajax, and displayed on the page using jQuery.
This works fine when there is only one element on the page with the class "saveTask", but if I have more than 1 form element with the class "saveTask" it stops functioning correctly, as the variable "var task" shows as "undefined" rather than the actual value of the form input.
Don't rely on the .parent() method. Use .closest('form') instead. So the following line:
var thisParent = $this.parent().parent()
should look something like this instead:
var thisParent = $this.closest('form');
EDIT:
Based on the updated information you provided, it looks like when you're trying to register the click event handler it's failing out for some reason. Try this javascript instead as it will make use of the live event so that all the newly added items on the page will automatically have the click event autowired to them.:
$(function(){
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
});
$('.saveTask').live('click', function() {
$this = $(this);
var thisParent = $this.closest('ul');
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
});
First turn the save task into a function:
(function($){
$.fn.saveTask= function(options){
return this.each(function(){
$this = $(this);
$this.click(function(){
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
});
});
return false;
})(jQuery)
When the app starts change the saveTask selector to this:
function saveTask(){
$('.saveTask').saveTask();
}
Then on your add function:
function addTask(){
$newTask = $("<div>Some Task stuff</div>");
$newTask.saveTask();
}
This code is written very quickly and untested but essentially create a jQuery extension that handles for data submission then when ever a task is created apply the save task extension to it.
I think you're looking for the live event.
Also, your code is a little awkward, since the click event is only added when the saveTask() function is called. In fact, the saveTask() function, doesn't actually save anything, it just adds the click event to the elements with the .saveTask class.
What is your HTML structure?
It looks like your code can't find the input.taskName element.
Try setting thisParent to something like $this.closest('form'). (Depending on your HTML)
You could try wrapping your click function in an each()
ie
function saveTask(){
$('.saveTask').each (function () {
$this = $(this);
$this.click(function() {
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
})
}
I find this helps sometimes when you have issues with multiple elements having the same class

Categories