How to implement same set of JavaScript/jQuery functions on multiple elements - javascript

I need to run same method for multiple div elements. The code is give here:
<div class="opage" id="oddPage">
<img>
</div>
<div class="epage" id="evenPage">
<img>
</div>
<div class="opage" id="oddPage">
<img>
</div>
<div class="epage" id="evenPage">
<img>
</div>
<div class="opage" id="oddPage">
<img>
</div>
<div class="epage" id="evenPage">
<img>
</div>
and JS code is:
function flip() {
document.getElementById("oddPage").style.webkitTransform = "rotateY(-180deg)";
document.getElementById("evenPage").style.webkitTransform = "rotateY(0deg)";
}
function flop() {
document.getElementById("oddPage").style.webkitTransform = "rotateY(0deg)";
document.getElementById("evenPage").style.webkitTransform = "rotateY(180deg)";
}
My requirement is if I click on odd page flip() is called and if I click on even page odd function is called.
I did it using
$(document).ready(function(){
$('.opage').click(flip);
$('.epage').click(flop);
});
It works fine on first odd and first even page page but not on next pages. Then I came to know that multiple divs cannot have same Ids. So changed ids to oddPage1, evenPage1, oddPage2, evenPage2, oddPage3, evenPage3 and then tried it with getElementbyClassName in flip() and flip() but it did not work at all.
Then i tried this also
$(document).ready(function(){
$('.opage').click(function(){
$('opage').css('-webkit-Transform', 'rotateY(-180deg)');
$('epage').css('-webkit-Transform', 'rotateY(0deg)';
});
$('.epage').click(function(){
$('opage').css('-webkit-Transform', 'rotateY(0deg)';
$('epage').css('-webkit-Transform', 'rotateY(-180deg)');
});
});
But it is not working. I am new to jquery and learning it gradually.

$('#oddPage').click(flip);
$('#evenPage').click(flop);
if there are multiple elements with this id, change it to a class because ids are unique and reference it with a .
$('.oddPage').click(flip);
$('.evenPage').click(flop);

Simply use the following w/Jquery:
function flip() {
//Something on odd page;
//Something on even page;
}
function flop() {
//Something on odd page;
// Something on even page;
}
$('#evenPage').click(function(){
flop();
});
$('#oddPage').click(function(){
flip();
});
If you have multiple uses of evenPage and oddPage you will need to change these to classes.

Related

find <div> in a reloaded HTML page and apply function to it

I have an HTML page that lays out div components and every div component call a function and pass this as an object. The div looks like this:
<div id="pull-requests-view">
<div class="green-header">This is the 1st title</div>
# this is the div that will flash on double click
<div class="green" ondblclick="flashAndMessage(this)" onclick="unblink(this)" id="tile0">
<img class="profile-photo" src="someImageURL">
<div class="pill-green">
<a class="hypLink" href="UNIQUE_LINK_FOR_EACH_DIV" target="_blank">tag information</a>
</div>
</div>
</div>
What's really happening here is that there are multiple divs like that with different id. When I click double click on the div its calls the flashAndMessage() with argument this which results in my div to blink and flash using JQuery fadeIn() and fadeOut().
Details aside, the actual problem is that I have polling implemented that re-renders the HTML including all the divs. So basically the flashing and blinking is lost once the page updates.
I have tried global variables that store the this object before the page reloads and tries to pass the variables to jQuery find() function so that flashAndMessage() could be re-applied.
However it is not working for me. Here are my functions:
function unblink(selector) {
$(selector).stop()
$(selector).fadeIn({opacity: 1})
}
function blink(selector) {
$(selector).fadeOut('slow', function () {
$(this).fadeIn('slow', function () {
blink(this);
});
});
}
function flashAndMessage(selector) {
var pullReqURL = $(selector).find('.hypLink').attr('href')
blinkList.push(selector) # this is where the `div` is stored before the page reloads
blink(selector)
}
Note: The blinkList is a global array that is defined on top of everything else. I have a loop that runs after the divs are reloaded and I do see those divs that I stored in the list. However, when I iterate through that list and pass the obj to the flashAndMessage(), it does not work. It feels like the object is not the same when re-drawn or it loses some identity.
Code snippet not work because of restrictions, but code is tested and functional.
function unblink(selector) {
$(selector).stop();
$(selector).fadeIn({opacity: 1});
sessionStorage.href = "";
}
function blink(selector) {
$(selector).fadeOut('slow', function () {
$(this).fadeIn('slow', function () {
blink(this);
});
});
}
function flashAndMessage(selector) {
sessionStorage.href = $(selector).find('.hypLink').attr('href');
blink(selector);
}
if (sessionStorage.href) {
flashAndMessage($("a[href='"+sessionStorage.href+"']").parent().parent());
}
<div id="pull-requests-view">
<div class="green-header">This is the 1st title</div>
<div class="green" ondblclick="flashAndMessage(this)" onclick="unblink(this)" id="tile0">
<img class="profile-photo" src="someImageURL">
<div class="pill-green">
<a class="hypLink" href="UNIQUE_LINK_FOR_EACH_DIV" target="_blank">tag information</a>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Assuming you have a parent to <div id="pull-requests-view"> that is not getting reloaded with your polling code, you should use event delegation (and not inline event handlers).
<div id="parent-id-that-isnt-updated">
<div id="pull-requests-view">
...
</div>
</div>
You can attach your event listeners to the parent that doesn't update and have it only trigger when the clicked element matches the selector:
var $staticParent = $('#parent-id-that-isnt-updated');
$staticParent.on('dblclick', '.green', function() {
flashAndMessage(this);
});
$staticParent.on('click', '.green', function() {
unblink(this);
});

How do I apply jQuery's slideToggle() to $(this) and do the opposite to all other elements?

What I'd like to do is have all elements of class collapsible_list not displayed by default (with one exception... see below*), and then toggle their display when their parent <div class="tab_box"> is clicked. During the same click, I'd also like for every other element of class collapsible_list to be hidden so that only one of them is expanded at any given time.
*Furthermore, when the page initially loads I'd also like to check to see if an element of collapsible_list has a child a element whose class is activelink, and if there is one then I'd like that link's parent collapsible_list element to be the one that's expanded by default.
Here's some sample html code:
<style>
.collapsible_list {
display: none;
}
.collapsible_list.active {
display: block;
}
</style>
<div id="sidebar">
<div class="tab_box">
<div class="collapsible_tab">2014</div>
<div class="collapsible_list panel-2014">
1
2
3
</div>
</div>
<div class="tab_box">
<div class="collapsible_tab">2013</div>
<div class="collapsible_list panel-2013">
<a class="activelink" href="/2013/1">1</a>
2
3
</div>
</div>
</div>
And here's where I'm currently at with the javascript (although I've tried a bunch of different ways and none have worked like I'd like them to):
$(document).ready(function() {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active");
$(".tab_box").click(function() {
$(this).children(".collapsible_list").toggleClass("active").slideToggle("slow", function() {
$(".collapsible_list.active:not(this)").each(function() {
$(this).slideToggle("slow");
});
});
});
});
I hope that's not too confusing, but if it is then feel free to let me know. Any help is much appreciated.
Since you have a dom element reference that needs to be excluded use .not() instead of the :not() selector
jQuery(function ($) {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active").show();
$(".tab_box").click(function () {
var $target = $(this).children(".collapsible_list").toggleClass("active").stop(true).slideToggle("slow");
//slidup others
$(".collapsible_list.active").not($target).stop(true).slideUp("slow").removeClass('active');
});
});
Also, instead of using the slide callback do it directly in the callback so that both the animations can run simultaniously
Also remove the css rule .collapsible_list.active as the display is controlled by animations(slide)
Try This.
$('.collapsible_tab a').on('click', function(e){
e.preventDefault();
$('.collapsible_list').removeClass('active')
$(this).parent().next('.collapsible_list').toggleClass('active');
});
Fiddle Demo
I think your code would be less complicated if you simply remembered the previously opened list:
jQuery(function($) {
// remember current list and make it visible
var $current = $('.collapsible_list:has(.activelink)').show();
$(".tab_box").on('click', function() {
var $previous = $current;
// open new list
$current = $('.collapsible_list', this)
.slideToggle("slow", function() {
// and slide out the previous
$previous.slideToggle('slow');
});
});
});
Demo

jquery mutiple div with a single definition script

i have this jQuery code:
$(document).ready(function () {
$("#hide").click(function () {
$("div1").hide();
});
$("#show").click(function () {
$("div1").show();
});
});
and this jsp/html
for{int=0;i<V_loopnumber;i++)
{
%>
<button id='show' height:10px>showit</button>
<div1>
something
<button id='hide' height:10px>hideit</button>
</div1>
<%
}
For example if I have 3 elements, it produces 3 divs. However,if I push the button all the divs will be showed or hided cause they got the same name.
how can I differentiate the button with the respective divs?
Your markup has a few problems. You can not assign the same ID twice. Also div1 is not a valid tag name.
Perhaps you can restructure your markup along the lines of the following example:
<div class="container">
<button class="show">showit</button>
<div class="inner">
something
<button class="hide">hideit</button>
</div>
</div>
I assigned the buttons classes instead of ids and got rid of the div1 elements.
Now you can listen for a click event on the buttons and hide the related elements using the .closest() (http://api.jquery.com/closest/) method like this:
$(".hide").click(function () {
$(this).closest(".inner").hide();
});
$(this).closest(".inner") will retrieve the the closest element with the class inner up in the dom tree.
$(".show").click(function () {
$(this).parent().find(".inner").show();
});
$(this).parent().find(".inner") will go up one level in the dom tree and find the element with the class inner.
http://jsfiddle.net/KGk7B/
First, element ids must be unique. Use a class instead. Second, <div1> isn't a valid tag. Use a div with a class instead. Third, use traversal functions to find the specific element to toggle.
$(document).ready(function () {
$(".hide").click(function () {
$(this).closest('.show-hide-container').hide();
});
$(".show").click(function () {
$(this).next('.show-hide-container').show();
});
});
for{int=0;i<V_loopnumber;i++)
{
%>
<button class='show' height:10px>showit</button>
<div class="show-hide-container">
something
<button class='hide' height:10px>hideit</button>
</div>
<%
}
id must be unique on your page, use class
<button class='show' height:10px>showit</button>
and use $(this) in event callback function instead of using selector
$(".hide").click(function(){
$(this).parent().hide(); // this is hard select of your div1, i wrote only for your html
});
IMPORTANT: Use div instead of div1, div1 tag is undefined.

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

hide one div when another is showing in jQuery?

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>
Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});
You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});
It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.
You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

Categories

Resources