Javascript Problem with Variables - javascript

I have created a function to showing a title text in a separate div, its wotks perfectly, but a have problems with "title" attribute, so i wonna delete it after tooltipp wenn be displayed. And on mouse ou show it agaiin, but the variable tooltipptext is empty... same one an idea?
var tooltipptext;
$(".infoimg").hover(function(event) {
tooltipptext = $(this).attr("title");
showToolTip(event, tooltipptext);
$(this).attr("title", "");
return false;
});
$(".infoimg").mouseout(function() {
$("#bubble_tooltip").hide();
$(this).attr("title", tooltipptext);
return false;
});

.hover(), when passed a single functions runs it on both mouseenter and mouseleave, clering the variable because this:
tooltipptext = $(this).attr("title");
runs again after $(this).attr("title", ""); ran already. Instead pass both functions to .hover(), like this:
var tooltipptext;
$(".infoimg").hover(function() {
tooltipptext = $(this).attr("title");
showToolTip(event, tooltipptext);
$(this).attr("title", "");
}, function() {
$("#bubble_tooltip").hide();
$(this).attr("title", tooltipptext);
});
Or since you're never seeing the title attribute on hover, store it once like this:
$(".infoimg").each(function() {
var title = $(this).attr("title");
$(this).data('title', title).attr('title','');
}).hover(function() {
showToolTip(event, $.data(this, 'title'));
}, function() {
$("#bubble_tooltip").hide();
});
This has the added benefit of working on any number of images :)

Related

array is not working in a function which is inside for loop of jquery

I am stuck at a point,its worpress mediauploader. I want to upload images, one function is for one image but I have several upload buttons with unique id so I want only one function for all thats why I created the loop, on click of each button media uploader open up but there is problem saving the selected image, I am not getting that image url in the value. pls help new to jquery and javascript. Tried various methods this is one of them
this is screenshot of thing that I want->here
jQuery(document).ready(function($){
var b = ["#upload-button-1", "#upload-button-2", "#upload-button-3","#upload-button-4","#upload-button-5","#upload-button-6","#upload-button-7","#upload-button-8"];
var d =[".procircle-1", ".procircle-2",".procircle-3",".procircle-4",".procircle-5",".procircle-6",".procircle-7",".procircle-8"];
var j;
var c = ["#grid-image-1", "#grid-image-2", "#grid-image-3","#grid-image-4","#grid-image-5","#grid-image-6","#grid-image-7","#grid-image-8"];
var i;
for(i=0; i<=b.length; i++)
{
for(j=0;j<=c.length;j++){
$(b[i]).on('click',function(e){
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame= wp.media({
title:'Choose a Picture for Procedure ',
button:{
text:'Choose Picture'
},
multiple:false
});
mediaUploader.on('select',function(){
attachment= mediaUploader.state().get('selection').first().toJSON();
$(c[j]).val(attachment.url);
$('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'});
});
mediaUploader.open();
});
}
}
});
I would suggest doing the following (if you must keep your ids etc):
$(document).on('click', '#upload-button-1, #upload-button-2, #upload-button-3, #upload-button-4, #upload-button-5, #upload-button-6, #upload-button-7, #upload-button-8', function(e) {
var match = e.target.id.match(/(\d+)/g);
e.preventDefault();
if(mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title:'Choose a Picture for Procedure ',
button:{
text:'Choose Picture'
},
multiple:false
});
mediaUploader.on('select', function(){
var attachment = mediaUploader.state().get('selection').first().toJSON();
var id = '#grid-image-' + match[1];
$(id).val(attachment.url);
$('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'});
});
mediaUploader.open();
});
This removes the loop and delegates your handler so you only create one click handler rather than one per loop iteration as you are currently, and also creates a single mediauploader select handler. Finally, match the corresponding input with the event target that performed the click. Should work, although you might need to play around with it a bit, and it could definitely be refactored to be nicer. Hope it helps.

JS popup does't works comparison operator

I have 5 link and mini preview photo and url 3 links its good link opsss and upsss is wrong when i click good link i'm going to new page when i click error link attr href change to adresError and then we have popup This only works for the first time second time click all links have a popup and should have only opsss and upsss
http://jsfiddle.net/3ptktp47/1/
Here is my code :
var nameError = [
"opsss",
"upsss",
];
$(function() {
$('#prev').hide();
$(function() {
var title_link = 'kliknij aby podejżeć';
$(".preview-link a")
.attr({title: title_link})
//.tooltip()
.click(function(){
$('.preview-link a img').css('opacity',1);
var sciezka = $(this).attr("href");
var tytul = $(this).attr("title");
var adres = $(this).text();
//alert(adres);
$(".duzy").attr({ src: sciezka, alt: tytul, style:'cursor:pointer;', href:'http://www.'+ adres,'target':'_blank'});
$('.link').html(adres).attr({href:'http://www.'+ adres,'target':'_blank'});
$('#prev').show();
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.link, .duzy').click(function(event){
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({href:'http://'+ adresError,'target':'_blank'});
});
};
if(adres == 'opsss.com'){
var adresError = 'x4ql.nazwa.pl/'+ nameError[0];
errorDomain();
}else if(adres == 'upsss.com' ){
var adresError = 'x4ql.nazwa.pl/'+ nameError[1];
errorDomain();
}else{
//$('#popup, .popup-bg').fadeOut();
};
$('.cancel, .popup-bg').click(function(event){
$('#popup, .popup-bg').fadeOut();
});
return false;
});
$('.close').click(function(){
$('#prev').hide();
});
$('.link').mouseover(function(){
$(this).css({style: 'color:#000;'});
});
});
});
EDITED:
Ok, I was able to handle your problem.
Your .click() event in the errorDomain() method was firing every time you clicked this square. I managed it to toggle a class on a.duzy element with toggleClass('error') in your if-statement where you check the address.
Inside your click() event, a if-statement is checking if the .duzy element has class named error with hasClass('error') , this has following result -
TRUE- your popup will be displayed
FALSE - nothing happens
I hope my answer is clear enough, but please check out the edited fiddle.
EDITED SOURCE:
Your errorDomain() Method
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.duzy, .link').click(function (event) {
if ($(this).hasClass("error")) {
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({
href: 'http://' + adresError,
'target': '_blank'
});
}
});
}
The if-statements
if (adres == 'opsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[0];
$('a.duzy').toggleClass("error");
errorDomain();
} else if (adres == 'upsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[1];
$('a.duzy').toggleClass("error");
errorDomain();
} else {
$('a.duzy').removeClass("error");
}
Edited fiddle

JavaScript changing image when hovering

I am trying to write a script, so that when someone hovers over an image, that same images changes to a different one, ie. I hover over up.png, and it changes to up_highlighted.png, when the mouse goes off the image it should change back.
However I can't seem to get it working despite all my attempts, here is the relevant code of what I have tried so far:
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up()\" onclick=\"increase_rating()\">";
function hover_up(){
$(document).ready(function() {
var oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').hover(function() {
//on hover of your element
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function() {
//when the cursor leaves your element
$('.thumbsbtn1').attr('src', oldSrc);
});
});
}
PS. I do not wish to use sprites.
Old School: http://jsfiddle.net/PAGUp/
var elem = document.getElementById('targetImg');
var oldSrc;
elem.onmouseover = function() {
oldSrc = elem.src;
elem.src = 'http://www.eclipse-developers.com/images/up_hover.png';
}
elem.onmouseout = function() {
if(typeof oldSrc !== 'undefined') {
elem.src = oldSrc;
}
}
I'm sure the jquery is more pithy. Essentially you need a variable to hold the 'old' src URL, and mouseover and mouseout handlers to set the new URL and back it out.
You don't have to wrap $(document).ready inside hover_up function. Note that I have removed onhover from HTML
Try
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onclick=\"increase_rating()\">";
$(document).ready(function() {
var oldSrc;
$(document).on('hover', '.thumbsbtn1', function () {
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}, function () {
$('.thumbsbtn1').attr('src', oldSrc);
});
});
try this
print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up(this)\" onclick=\"increase_rating()\" onmouseout=\"hover_out(this)\">";
var oldSrc;
function hover_up(e){
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}
function hover_out(e){
$('.thumbsbtn1').attr('src',oldSrc);
}

how to fix my JQuery bug?

The script is on jsfiddle here : CODE
What it does at the moment: it's a form that have two types of URL field textarea and input, it converts the texts in those fields to a link to be click-able.
How it works: if you click next to the link/links you can edit the link or on a double click on the link. IF you click once on the link it takes you to that page.
Last update: i added the .trigger('blur'); on the last line, Because before i did that, the text area was showing the links like one merged link, for example : test.com and test2.com were showing test.comtest2.com, after i added this last update, the split for textera work also on the load of page not just on the edit of textarea ( it was working without the last update but only when you edit the textarea and put between links a space, and i want it to be working on the load of page because the textarea format was sent already as one link pre row ).
My problem: after i did this last update, the double click is messed up, it should just be able to edit the link and don't go to that page unless one click, but now it edits it and in like one second it goes also to that page. I want the double click just to edit without going to that page. and to go only with one click.
Thanks a lot in advance!
The code also here:
$('.a0 a').click(function(){
var href = $(this).attr('href');
// Redirect only after 500 milliseconds
if (!$(this).data('timer')) {
$(this).data('timer', setTimeout(function () {
window.open(href, '_blank')
}, 500));
}
return false; // Prevent default action (redirecting)});
$('.a0').dblclick(function(){
clearTimeout($(this).find('a').data('timer'));
$(this).find('a').data('timer', null);
$(this).parent().find('input,textarea').val($(this).find('a').text()).show().focus();
$(this).hide();})
$('.a0').click(function(){
$(this).parent().find('input,textarea').val($.map($(this).find('a'),function(el){return $(el).text();}).join(" ")).show().focus();
$(this).hide();})
$('#url0, #url1,#url4').each(
function(index, element){
$(element).blur(function(){
var vals = this.value.split(/\s+/),
$container = $(this).hide().prev().show().empty();
$.each(vals, function(i, val) {
if (i > 0) $("<span><br /></span>").appendTo($container);
$("<a />").html(val).attr('href',/^https?:\/\//.test(val) ? val : 'http://' + val).appendTo($container);;
}); })
}).trigger('blur');
A double-click is always predeeded by the following chain of events:
mousedown, mouseup, click, mousedown, mouseup, click, dblclick
You can make your click-events wait and check if a double-click event happened afterwards. setTimeout is your friend. Be sure to copy any data you need from the event object passed to your handler. That object is destroyed after the handler finished - which is before your delayed handler is invoked.
You can manually dispatch a double click event to prevent click-events from being executed prior to them. See the Fiddle
// ms to wait for a doubleclick
var doubleClickThreshold = 300;
// timeout container
var clickTimeout;
$('#test').on('click', function(e) {
var that = this;
var event;
if (clickTimeout) {
try {
clearTimeout(clickTimeout);
} catch(x) {};
clickTimeout = null;
handleDoubleClick.call(that, e);
return;
}
// the original event object is destroyed after the handler finished
// so we'll just copy over the data we might need. Skip this, if you
// don't access the event object at all.
event = $.extend(true, {}, e);
// delay click event
clickTimeout = setTimeout(function() {
clickTimeout = null;
handleClick.call(that, event);
}, doubleClickThreshold);
});
function handleClick(e) {
// Note that you cannot use event.stopPropagation(); et al,
// they wouldn't have any effect, since the actual event handler
// has already returned
console.log("click", this, e);
alert("click");
}
function handleDoubleClick(e) {
// this handler executes synchronously with the actual event handler,
// so event.stopPropagation(); et al can be used!
console.log("doubleclick", this, e);
alert("doubleclick");
}
jsfiddle refuses to load on my connection for some reason, so cant see the code.
Based on your explanation i suggest you look into event.preventDefault to add more control on what should happen on your click events. This could be used in conjunction with #rodneyrehm's answer.
Refer to my previous answer.
For your quick reference, I have pasted my answer here
$('.a0 a').click(function(){
var href = $(this).attr('href');
// Redirect only after 500 milliseconds
if (!$(this).data('timer')) {
$(this).data('timer', setTimeout(function() {
window.open(href, '_blank')
}, 500));
}
return false; // Prevent default action (redirecting)
});
$('.a0').dblclick(function(){
var txt = document.createElement('div');
$.each($(this).find('a'), function(i, val) {
clearTimeout($(val).data('timer'));
$(val).data('timer', null);
$(txt).append($(val).text());
$("<br>").appendTo(txt);
});
var content = $(this).parent().find('input,textarea');
var text = "";
$.each($(txt).html().split("<br>"), function(i, val) {
if (val != "")
text += val + "\n";
});
$(content).html(text);
$(this).hide();
$(content).show().focus();
})
$('#url0, #url1, #url4').each(function(index, element) {
$(element).blur(function(){
if ($(this).val().length == 0)
$(this).show();
else
{
var ele = this;
var lines = $(ele).val().split("\n");
var divEle = $(ele).hide().prev().show().empty();
$.each(lines, function(i, val) {
$("<a />").html(val).attr({
'href': val,
'target': '_blank'}).appendTo(divEle);
$("<br/>").appendTo(divEle);
});
}
});
});
​

get id of child element when parent is clicked

Hello I have seen similar posts but none answer what I want to accomplish
I made a sample here
http://jsfiddle.net/edgardo400/R6rVJ/
What i basically want is when a click happens in the parent you get the id of the child
and store it in a variable so i can pass the variable currentID to the code below otherwise I will have to replicate this code 9 times for each id from box1 to box9
jQuery(currentID).delegate("a", "hover", function(event){
var $img = jQuery(this).parent("li").find('img');
var image = jQuery(this).attr('data-img');
jQuery('.defaultimg').stop(true, true).fadeOut();
if( event.type === 'mouseenter' ) {
if($img.length){
$img.show();
}else{
jQuery(this).parent("li").append('<img id="theImg" src="' + image + '" />');
}
}else{
if($img){
$img.hide();
}
jQuery('.defaultimg').stop(true, true).fadeIn();
}
});
});
$('#boxes').on('click', function(e) {
var currentID = e.target.id;
console.log(currentID);
......rest of code
In javascript it would be:
var a = document.getElementById('#boxes');
a.onclick = function(e){
console.log(e.target.id);
}
If you only wish to make your code working and displaying on your console the box name, you should probably set
jQuery('#boxes').bind('click', function(event) {
var currentID = jQuery(event.srcElement).attr('id');
/* rest of your code */
});
You might want to do something easier
jQuery('#boxes').children().bind('click', function() {
jQuery(this).delegate...
});
Although I'm not sure why you are doing this ...
fixed http://jsfiddle.net/nxTDA/

Categories

Resources