I'm using jquery data() to attach the name of a div I'd like to show when another div (.panel_button) is clicked. I'm doing the attaching of this div's id to the button when the document is ready. Is this an okay way to do this? Or is it too resource intensive and unprofessional-looking?
$(document).ready(function(){
$('#sample_button').data('panel', 'sample_kit_container');
$('#mail_button').data('panel', 'mail_container');
$('#mbillboard_button').data('panel', 'mbillboard_container');
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
$('#' + panel).show();
});
});
Yeah, that should work just fine. As an alternate, you could store the actual element itself (assuming it already exists) rather than finding it each time:
$('#sample_button').data('panel', $('#sample_kit_container'));
$('#mail_button').data('panel', $('#mail_container'));
$('#mbillboard_button').data('panel', $('#mbillboard_container'));
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
panel.show();
});
Another option would be to store the actual jQuery element in the data property, so no need to do a second selection:
$(function(){
$('#sample_button').data('panel', $('#sample_kit_container'));
$('#mail_button').data('panel', $('#mail_container'));
$('#mbillboard_button').data('panel', $('#mbillboard_container'));
$('.panel_button').on('click', function(){
$('.secondary_panel').hide();
var panel = $(this).data('panel');
panel.show();
});
});
#thomas, in my opnion, your solution is actually better than those in the other answers.
Including the whole object inside the data attribute may not always work. For example, what if the $('#sample_kit_container') object doesn't exist on load, but rather ofter an ajax load.
...
Only one tiny comment! why don't you call the data object: panelId. It would be more a bit intuitive.
Related
I'm trying to create a more generic local-storage setup for my application so I don't have to create a function for each time I add a new element to the page that I want to store in local storage. I have my jquery setup like so.
/* SET LOCAL STORAGE */
$( document ).on( "keyup",".localStorage",function(){
var id = $(this).attr('id');
if(id) {
id = "#" + id;
localStorage.setItem(id, $(this).val());
}
});
The part that seems to be having some difficulty, is when the page is loaded, looping through each ".localStorage" element and applying the proper data (somewhat like saving as a draft).
I can't seem to use jQuery's $each() function, as that doesn't work with elements loaded through $ajax().
So what's the best way to find elements on a page even if they are loaded dynamically? Any help is greatly appreciated. Thanks!
You CAN in fact access elements added dynamically to the page. I would just try something like this in your event code:
var elements = $('.localstorage');
for (var i in elements) {
doStuf(elements[i]);
}
Weird problem. I'm modifying shop template:
https://demo.themeisle.com/shop-isle/product-category/clothing/dresses/
At this moment when you hover product's picture there will show "add to cart" button. This is .
Under picture there is price
I prepared code:
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
Nothing happens. This code work only if I set timeout:
setTimeout(function() {
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
}, 10000);
Of course timeout it's not a solution. I was trying to find out minimal time to obtain best behavior but it's impossible. I have feeling that every browser (and version...) needs personalized time setting.
I thought that after 24-hour break I will get some brillant idea, but that doesn't work, no more ideas.
--- EDIT ---
OK, thanks for pointed mixed common js with jquery - I will correct that later.
jQuery(document).ready(function(){
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
console.log(el);
});
});
That's logical that var from should be inside ready but this still doesn't work. No effect.
If I use in loop console.log it will return for me html code of el.
--- EDIT ---
Thanks. While testing I noticed something. I wanted append element .woocommerce-Price-amount.amount to element .product-button-wrap. But how can I do that if element .product-button-wrap isn't originally in source? This object is created dynamically (I don't know how).
-- EDIT --
OK. I checked JS files and found code adding to DOM .product-button-wrap so I putted my code there and now everything works. Thanks for help.
The problem is because you're running your code before the DOM has loaded. You need to retrieve the elements within the document.ready event handler.
Also note that you have an odd mix of native JS and jQuery methods. I'd suggest using one or the other, like this:
jQuery(function($) {
$('.woocommerce-Price-amount.amount').each(function() {
$(this).parent().parent().find('.product-button-wrap').append(this);
});
});
Also note that .parent().parent() should be replace by a single call to closest(), but I can't give you an exact example of that without seeing your HTML.
I'm fairly new to Javascript, and am trying to get an 'on click enlarge' kind of effect, where clicking on the enlarged image reduces it again. The enlarging happens by replacing the thumbnail by the original image. I also want to get a slideshow using images from my database later on.
In order to do that, I made a test where I replace the id which indicates enlarging is possible by a class and I also use a global variable so that I can keep a track of the url I'm using. Not sure this is the best practice but I haven't found a better solution.
The first part works fine, my image gets changed no problem, values are also updated according to the 'alert' statement. However, the second part, the one with the class never triggers.
What am I doing wrong (apart from the very likely numerous bad practices) ?
If instead of changing the class I change the id directly (replacing .image_enlarged by #image_enlarged, etc.), it seems to call the first function, the one with the id, yet outputs the updated id, which is rather confusing.
var old_url = "";
$(function(){
$('#imageid').on('click', function ()
{
if($(this).attr('class')!='image_enlarged'){
old_url = $(this).attr('src');
var new_url = removeURLPart($(this).attr('src'));
$(this).attr('src',new_url); //image does enlarge
$(this).attr('class',"image_enlarged");
$(this).attr('id',"");
alert($(this).attr('class')); //returns updated class
}
});
$('.image_enlarged').on('click', function (){
alert(1); //never triggered
$(this).attr('src',old_url);
$(this).attr('class',"");
$(this).attr('id',"imageid");
});
});
function removeURLPart(e){
var tmp = e;
var tmp1 = tmp.replace('thumbnails/thumbnails_small/','');
var tmp2 = tmp1.replace('thumbnails/thumbnails_medium/','');
var tmp3 = tmp2.replace('thumbnails/thumbnails_large/','');
return tmp3;
}
As for the html, it's really simple :
<figure>
<img src = "http://localhost/Project/test/thumbnails/thumbnails_small/image.jpg" id="imageid" />
<figcaption>Test + Price thing</figcaption>
</figure>
<script>
document.write('<script src="js/jquery-1.11.1.min.js"><\/script>');
</script>
<script type="text/javascript" src="http://localhost/Project/js/onclickenlarge.js"></script>
From the API: http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected
set of elements in the jQuery object.
When you do $('.image_enlarged').on(...) there is no element with that class. Therefore, the function is not registered in any element.
If you want to do so, then you have to register the event after changing the class.
Here's an example based on your code: http://jsfiddle.net/8401mLf4/
But this registers the event multiple times (every time you click) and it would be wrong. So I would do something like:
$('#imageid').on('click', function () {
if (!$(this).hasClass('image_enlarged')) {
/* enlarge */
} else {
/* restore */
}
}
JSfiddle: http://jsfiddle.net/8401mLf4/2/
Try using:
addClass('image-enlarged')
instead of:
.attr('class',"image_enlarged");
the best way to do this would be to have a small-image class and a large image class that would contain the desired css for both and then use addClass() and removeClass depending on which you wanted to show.
I have this following jquery on my view:
$(document).ready(function() {
$(function() {
$('#link1').click(function() {
$('#link2').show();
$('#link1').hide();
$('#frame').attr('src', 'http://google.com/');
});
});
});
$(document).ready(function() {
$(function() {
$('#link2').click(function() {
$('#link1').show();
$('#link2').hide();
$('#frame').attr('src', 'http://yahoo.com/');
});
});
});
On pageload, the link2 is set to hide. What the jQuery does is: when the link with id link1 is clicked, it will show the link with idlink2 and hide itself. And vice versa.
My problem is it seems that my jQuery code can still be simplified. Is there other ways I can do what I wanted with simpler version? Thanks for the help!
Working example : http://jsfiddle.net/cuJBm/
$(document).ready(function() {
$(function() {
var linkSet = $('#link1').add('#link2')
linkSet.click(function() {
linkSet.toggle();
});
});
});
The add method allows you to add a different selector to the set of matchers, thus binding both clicks simultaneously. By saving the constructed set to a variable (linkSet), it stops you from having to traverse the DOM twice.
The only two assumption made here, are
1) That in the initial state only one is visible.
2) That the id structure is meaningful, useful, and classes will not suffice.
http://jsfiddle.net/cuJBm/1/
To answer your second question about setting an attribute on #frame. There are numerous ways of doing this. Perhaps the simplest is to add the following to your .click handler (after the toggle).
if ($(this).attr('id')=='link1'){
$('#frame').attr('src', 'www.google.com');
} else if ($(this).attr('id')=='link2'){
$('#frame').attr('src', 'www.yahoo.com');
}
Personally, I would probably add a custom attribute to your link elements, something like:
<a id='link1' iframe-source='www.google.com'>
<a id='link2' iframe-source='www.yahoo.com'>
And then: (again, just after the toggle):
source = $(this).attr('iframe-source');
$('#frame').attr(src, source);
The reason for saving source if is that if you attempt to get $(this) within the .attr on $('frame'), it will (as always) return the currently matched element, ie $('#frame').
Alternately (and very similiarly to the above approach), you could use the innerHTML of the link. For example:
<a id='link1'>link1<span style="display:none">www.google.com</span></a>
<a id='link2'>link2<span style="display:none">www.yahoo.com</span></a>
And then: (again, just after the toggle):
source = $(this).find('span').text();
$('#frame').attr(src, source);
Personally, I dislike this last method as it pollutes the DOM structure, leading to slightly more expensive rendering times, and (in my opinion) less readable code. Practically, all three methods work just fine.
<p class="link" style="display:none;" data-link="http://google.com/">sfdf</p>
<p class="link" data-link="http://yahoo.com/">ee</p>
$('.link').click(function() {
$('.link').toggle();
$('#frame').text($(this).data("link"));
});
jsfiddle :http://jsfiddle.net/xqDus/1/
Use jQuery toggle()
just add this
Google
Yahoo
target is id of the frame
$(function() {
$('#link1, #link2').click(function() {
$('#link1, #link2').toggle();
});
});
Imagine a normal page calling javscript in head. The trouble is some of the content isnt loaded untill i click on a link. Subsequently when this link loads the content it wont work. This is because i guess the javascript has already been run and therefor doesnt attach itself to those elements called later on. There is only standard html being called.
So for example this is the code which calls my external html.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).slideDown('slow');
});
});
If the html i was calling for example and H1 tag was already in the page the cufon would work. However because i am loading the content via the above method H1 tags will not be changed with my chosen font.This is only an example. The same will apply for any javascript.
I was wonering whether there is a way around this without calling the the javascript as well the html when its received from the above function
If you want to attach events to elements on the page that are dynamically created take a look at the "live" keyword.
$('H1').live("click", function() { alert('it works!'); });
Hope this is what you were looking for.
Does Cufon.refresh() do what you want?
As you said Cufon was just an example, I'd also suggest a more general:
$.get(url, options, function(html, status) {
var dom = $(html);
// call your function to manipulate the new elements and attach
// event handlers etc:
enhance(dom);
// insert DOM into page and animate:
dom.hide();
$target_element.append(dom); // <-- append/prepend/replace whatever.
dom.show(); // <-- replace with custom animation
});
You can attach event handlers to the data that you get via the get() inside of the callback function. For example
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).find('a').click(function(e) {
// specify an event handler for <a> elements in returned data
}).end().slideDown('slow');
});
});
live() may also be an option for you, depending on what events you want to bind to (since live() uses event delegation, not all events are supported).
Andy try this. It will call the Cufon code after each AJAX request is complete and before the html is actually added to the page.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data);
Cufon.replace('h1');
$(this).slideDown('slow');
});
});
JavaScript is not executed because of a security reason OR beccause jQuery is just setting this element's innerHTML to some text (which is not interpreted as a JavScript) if it's contained. So the security is the beside effect.
How to solve it?
try to find all SCRIPT tags in Your response and execute them as fallows:
var scripts = myelement.getElementsByTagName("SCRIPT");
var i = 0;
for (i = 0; i < scripts.length; i++)
eval(scripts[i].innerHTML);