html head:
<script type="text/javascript" language="JavaScript">
function getStyle() {
var temp = document.getElementById("cont").style.display;
return temp;
}
function switch01() {
var current = getStyle();
if (current == "none") {
document.getElementById("cont").style.display = "block";
}
else {
document.getElementById("cont").style.display = "none";
}
}
</script>
body:
CONTENT
CSS:
#cont{
display: none;
}
After loading the page - first click doesn't work. After the first click - everything works.
Also, How could I show/hide the div slowly (with sliding effect, not momentally) ?
The value you get for the first time is "undefined".
You can:
1) Set the value via javascript when page loads;
document.getElementById("cont").style.display = "none";
or
2) decode "undefined" value to none, because you know that at first the value will be none;
var temp = document.getElementById("cont").style.display;
if (temp == "undefined")
temp = "none";
return temp;
both pretty ugly solutions, but they work.
If it must be inline you need to do this DEMO
CONTENT
and this (reversing the test for none to be a test for not block)
<script type="text/javascript" language="JavaScript">
function switch01(objId) {
var current = document.getElementById(objId).style.display;
document.getElementById(objId).style.display=(current!="block")?"block":"none";
return false
}
</script>
The above ANSWERS your question
UPDATE: Since it seems you would like jQuery instead, here is how you need to code that - notice the return false which Michal missed.
CONTENT
$(function() { // wait for the page to load
$('#toggle').on("click",function(e) { // when link clicked
$('#cont').slideToggle(); // slide open or closed
return false; // or e.preventDefault(); // stop the click executing the href
});
});
If you want the slide effect, my recommendation is using jQuery:
$('#toggle').click(function() {
$('#cont').slideToggle();
});
See this DEMO.
For changing the sliding speed and more information see documentation.
For hiding the div.. you can take a look at
$('cont').hide(); function.
More relevant Information is available here :
http://api.jquery.com/hide/
http://api.jquery.com/show/
And for sliding effect Jquery is top notch in this department. You just have to pass the argument as given below.. and it does the work.
$("cont").click(function () {
$(this).hide("slide", { direction: "down" }, 1000);
});
FYI : http://docs.jquery.com/UI/Effects/Slide
Related
I am trying to convert the JavaScript to jQuery for my carousel.
The code I had is:
document.querySelectorAll('.indicators')[0].style.color = 'red';
document.querySelector('.toggler-prev').style.display = 'none';
document.addEventListener('postchange', function(event){
document.querySelectorAll('.indicators')[event.lastActiveIndex].style.color = 'white';
document.querySelectorAll('.indicators')[event.activeIndex].style.color = 'red';
var togglerPrev = document.querySelector('.toggler-prev');
var togglerNext = document.querySelector('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.style.display = 'block';
togglerNext.style.display = 'none';
} else if (event.activeIndex === 0) {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'none';
} else {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'block';
}
});
Which I transferred to jQuery:
$('.indicators').css('color','#000');
$('.toggler-prev').css('display','none');
$(window).on('postchange', function(event){
$('.indicators')[event.lastActiveIndex].css('color','#FFF');
$('.indicators')[event.activeIndex].css('color','#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.css('display','block');
togglerNext.css('display','none');
} else if (event.activeIndex === 0) {
togglerNext.css('display','block');
togglerPrev.css('display','none');
} else {
togglerNext.css('display','block');
togglerPrev.css('display','block');
}
});
But it isn't working as I expected for example togglers are not being hidden and color of indicators not being changed.
This is the working JS example: http://codepen.io/anon/pen/eJYWQO
And my jQuery alternative: http://codepen.io/anon/pen/eJYWrq
Can anybody help me with editing my second codepen? Thanks in advance.
You forgot to mention somewhere that you are using AngularJS and onsenUI ;)
Your problem is, that the jQuery event does not have the properties activeIndex and lastActiveIndex, but they can be found in event.originalEvent.
Also, like #stalin said in his answer, your indicators are no jQuery objects, therefore you can't call the css-function on them. Wrap this stuff in another jQuery constructor like $() or even better, use the eq-function which returns a jQuery wrapped object from an array.
Then, to optimize some of the readability, you might want to consider the hide and show function instead of changing the CSS property display.
All in all your code should look like this
$('.indicators').css('color', '#fff');
$('.indicators').eq(0).css('color', '#000'); // highlight the first indicator
$('.toggler-prev').hide();
$(window).on('postchange', function(event) {
//store the indices for readability
var activeIndex = event.originalEvent.activeIndex;
var lastActiveIndex = event.originalEvent.lastActiveIndex;
$('.indicators').eq(lastActiveIndex).css('color', '#FFF');
$('.indicators').eq(activeIndex).css('color', '#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (activeIndex === carousel.getCarouselItemCount() - 1) {
togglerPrev.show();
togglerNext.hide();
} else if (activeIndex === 0) {
togglerNext.show();
togglerPrev.hide();
} else {
togglerNext.show();
togglerPrev.show();
}
});
You have several problems in your implementation
First the event is not trigered in $(window) is in the $(document)
Your variable like lastActiveIndex are not in the event object are in event.originalEvent
$('.indicators')[event.lastActiveIndex] return a dom object not a jquery object you need to wrap this result in a jquery object to use the css() function
After you fix all this your code will work
Sorry that don't have time for create a fiddle for you :)
I have this JavaScript to make the div flash every two seconds. I was wondering if I could add anything into this current function so that the div fades in and out instead of appearing and disappearing with no transition.
JavaScript
<script language = "javascript">
function flash()
{
var blinker = 2000
var timeIn = setInterval(function() {
var element = document.getElementById('sign');
element.style.visibility = (element.style.visibility == 'hidden' ? '' : 'hidden');
}, blinker);
}
</script>
HTML div
<div class = "sign" id = "sign">
<p> hello </p>
</div>
Since you've tagged jQuery, you can simplify it to:
$('#sign').fadeIn(2000); // fade-in in 2 seconds
and
$('#sign').fadeOut(2000); // fade-out in 2 seconds
or as pointed out by user: Bondye
function flash() {
$('#sign').fadeToggle(2000);
}
If you want it to continue fading in and out.. you could try something like this:
function keepFading($obj) {
$obj.fadeToggle(2000, function () {
keepFading($obj)
});
}
keepFading($("#sign"));
See working example in Fiddle
This function would then work on any jquery object you pass it. So if you have something else you want to do the same thing you can just call it like keepFading($("#someOtherEle"));
For this to work, you'll need to make sure that jquery is included. You can then put the above code at the bottom of your html... or in your head if you wrap in a $(document).ready( ... )
You can implement fadeIn and fadeOut on pure javascript:
function fadeOut(id,val){
if(isNaN(val)){
val = 9;
}
document.getElementById(id).style.opacity='0.'+val;
//For IE
document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
if(val>0){
val–;
setTimeout('fadeOut("'+id+'",'+val+')',90);
}else{
return;
}
}
function fadeIn(id,val){
// ID of the element to fade, Fade value[min value is 0]
if(isNaN(val)){
val = 0;
}
document.getElementById(id).style.opacity='0.'+val;
//For IE
document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
if(val<9){
val++;
setTimeout('fadeIn("'+id+'",'+val+')',90);
}else{
return;
}
}
Here's a FIDDLE
setInterval(function() {
$('.sign').animate({ opacity: '0' }, 800).animate({ opacity: '1' }, 800);
}, 2000);
It is also possible to fadeToggle with jQuery. See details here:
http://api.jquery.com/fadeToggle/
<script>
function flash(id) {
$('#'+id).fadeToggle();
}
var blinker = 2000;
var timeIn = setInterval(function() {
flash('sign');
}, blinker);
</script>
I have the following j-query code (using the jquery plugin ajax/libs/jquery/1.10.1) to move a div element to the left upon clicking on a separate div element:
<script>
$(document).ready(function(){
$("#tab_box3").click(function(){
$.fx.speeds._default = 800;
$("#tab3").animate({left:"+=97%"});
});
});
</script>
What I want to happen is when the #tab_box3 div is clicked on a second time, the #tab3 div moves back to where it originally started.
I tried the following, using Toggle, but it does not seem to have worked:
<script>
$(document).ready(function(){
$("#tab_box3").click(function(){
$.fx.speeds._default = 800;
$("#tab3").animateToggle({left:"+=97%"});
});
});
</script>
Can anyone offer advice please?
You must doing something like this :
$(document).ready(function(){
$("#tab_box3").click(function(e){
var element = $(this),
clicked = parseInt(element.data('clicked')) || 0;
element.data('clicked', clicked + 1);
$("#tab3").stop();
if (clicked % 2 == 0)
{
$("#tab3").animate({left:"+=97%"}, 800);
}
else
{
$("#tab3").animate({left:"-=97%"}, 800);
}
e.preventDefault();
});
});
An example here :
http://jsfiddle.net/Q5HDu/
You will have to use -=97% to offset the previous animation change.
var $tab3 = $("#tab3");
if ($tab3.data("animated")) {
$tab3.animate({left: "-=97%").data("animated", false);
}
else {
$tab3.animate({left: "+=97%").data("animated", true);
}
I'm using jquery and ajax to create a drawer (#DrawerContainer) and load content into it if I click a thumbnail in a gallery. My function is almost finished but I want to be able to close that drawer if I click again the opening button (now #current).
Here is a jsfiddle of my code: http://jsfiddle.net/RF6df/54/
The drawer element appears if you click a square/thumbnail, it's the blueish rectangle.
The current thumbnail is turned green.
I added a button in my drawer (not visible in the jsfiddle) to close it. I use this part of code for this purpose and it's working like a charm.
// Close the drawer
$(".CloseDrawer").click(function() {
$('#DrawerContainer').slideUp()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
Now I need my #current div to be able to close #DrawerContainer the same way .CloseDrawer does in the code above. Unfortunately adding a second trigger like this $("#current,.CloseDrawer").click(function() to my function isn't working... When clicking my "current" thumbnail, it just reopen the drawer instead of closing it...
How can I modify my code to close my #DrawerContainer with the "current" thumbnail?
Please keep in mind that I'm learning jquery, so if you can comment it could be of a great help. And please do not modify my markup or css, since everything works beside the closing part.
As per my understanding, you can use "toggle()" function which does exactly the same (i.e, toggle visiblity).
$('#DrawerContainer').toggle();
EDIT:
Updated the script to work.
$(document).ready(function() {
$.ajaxSetup({cache: false});
$('#portfolio-list>div:not(#DrawerContainer)').click(function() {
if ($(this).attr("id") != "current")
{
// modify hash for sharing purpose (remove the first part of the href)
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
$('#current').removeAttr('id');
$(this).attr('id', 'current');
// find first item in next row
var LastInRow = -1;
var top = $(this).offset().top;
if ($(this).next().length == 0 || $(this).next().offset().top != top) {
LastInRow = $(this);
}
else {
$(this).nextAll().each(function() {
if ($(this).offset().top != top) {
return false; // == break from .each()
}
LastInRow = $(this);
});
}
if (LastInRow === -1) {
LastInRow = $(this).parent().children().last();
}
// Ajout du drawer
var post_link = $(this).find('.mosaic-backdrop').attr("href");
$('#DrawerContainer').remove(); // remove existing, if any
$('<div/>').attr('id', 'DrawerContainer').css({display: 'none'}).data('citem', this).html("loading...").load(post_link + " #container > * ").insertAfter(LastInRow).slideDown(300);
return false; // stops the browser when content is loaded
}
else {
$('#DrawerContainer').slideUp(300);
$(this).removeAttr("id");
}
});
$(document).ajaxSuccess(function() {
Cufon('h1'); //refresh cufon
// Toggle/close the drawer
$("#current,.CloseDrawer").click(function() {
$('#DrawerContainer').slideToggle()
setTimeout(function(){ // then remove it...
$('#DrawerContainer').remove();
}, 300); // after 500ms.
return false;
});
});
//updated Ene's version
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#!' , '' , hash );
$('a[href$="'+hash+'/"]').trigger('click');
}
});
Also, updated it here: Updated JS Fiddle
EDIT -2: Updated Link
Hope this Helps!!
I am using this Jquery and it works great
The problem is when i click on the button the page jumps all the way to the top. I am using Miva if that makes a difference
$(document).ready(function(){
$('.drop').click(function(){
var $next = $(this).parent().next('li.drop_down');
if($next.is(':visible')) {
$next.slideUp();
} else {
$next.slideDown();
}
});
});
Try adding "return false" to the end of your click() function.
Edit: (adding code example)
$(document).ready(function(){
$('.drop').click(function(){
var $next = $(this).parent().next('li.drop_down');
if($next.is(':visible')) {
$next.slideUp();
} else {
$next.slideDown();
}
return false;
});
});