jquery show and hide - javascript

i have a javascript code that when a link is clicked, it can show and hide divisions of the page.
function shoh(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
$(id).fadeIn();
} else {
$(id).hide();
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
} else {
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
document.all.id.style.display = 'none';
}
}
}
}
however it now doesn't work when i added the jquery fadeIn and hide instead of using the document.getElementByid method. why?

In order to select an element by id with jQuery, you have to use the selector syntax which means appending a # to the id. So, change
$(id).fadeIn();
to
$("#" + id).fadeIn();

Try this:
function shoh(id) {
var el = $('#' + id);
if (el.is(':visible')) {
el.hide();
} else {
el.fadeIn();
}
}

Due jquery works for you, you won't write crossbrowser code.
So simply
var $el = $('#'+id); // <-- this is the main key :-)
if ($el.css('display') == "none"){
$el.fadeIn();
} else {
$el.hide();
}

You could just declare it as a variable and then wrap it in a jQuery selector:
var $el = $(document.getElementById(id));
// if
$el.fadein();
//else
$el.hide();
jsFiddle

Related

Why does my JS 'click event' only run once?

I created a click event that opens a previously 'hidden' div and closes it again once you click the same button.
However, it only runs once (one open and one close) - I'm at a loss to explain why it doesn't work if I click it again.
let readMore = document.getElementById('clickAbout');
let moreInfo = document.getElementById('about');
let changeSepa = document.getElementById('sepChange');
readMore.addEventListener('click', function(){
changeSepa.style.height = '2rem';
if (moreInfo.className == "") {
moreInfo.className = "open";
moreInfo.style.display = 'block';
} else {
moreInfo.style.display = 'none';
}
});
this happens because you're checking if className == "", but you are modifying the className to be "open". On the second click it checks the className which is now "open" and goes to the else block. On the third click you expect for it to go into the first block but the className is still "open".
For an easy fix just change the className in the else block
else {
moreInfo.className = "";
moreInfo.style.display = 'none';
}
Also i suggest you make use of the classList property on elements
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
using the class list it could look like this:
readMore.addEventListener("click", function () {
changeSepa.style.height = "2rem";
if (moreInfo.className == "") {
moreInfo.classList.add("open");
moreInfo.style.display = "block";
} else {
moreInfo.classList.remove("open");
moreInfo.style.display = "none";
}
});
Or even
readMore.addEventListener("click", function () {
changeSepa.style.height = "2rem";
moreInfo.classList.toggle("open");
if (moreInfo.className == "") {
moreInfo.style.display = "block";
} else {
moreInfo.style.display = "none";
}
});

jQuery - Input change event not firing on mobile / iPhone / iPad [duplicate]

I did everything I could to make it happen, but without success.
The problem is that I create an element on runtime then bind a function to the element like the following code:
$(document).ready(function() {
$('.rem').click(function() {
$("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
});
$('#runtime').bind('click', func_name());
});
//End of doc
function func_name() {
alert('I got it!');
}
In the HTML code I have a label like below:
<div id="body">
<label class="rem">click me</label>
</div>
My second attempt
$(document).ready(function() {
$('.rem').click(function() {
$("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
});
$('#runtime').bind('click',function() {
alert($(this).text());
});
});
//End of doc
HTML code:
<div id="body">
<label class="rem">click me</label>
</div>
Change
$('#runtime').bind('click',func_name());
to
$('#runtime').live('click',func_name);
or (as of jQuery 1.7):
$('#runtime').on('click',func_name);
Two things to note:
I changed func_name() to func_name. You don't want to call the function when you bind the handler - you just want to reference it.
Calling bind won't do you any good, because #runtime doesn't exist until after you've clicked .rem. That's why you need either live or on (depending upon your jQuery version).
And just for good measure: here's a good reference on why you should be using jQuery.on anyway.
You don't want to run the function at the point in the code, so remove the ():
$('#runtime').bind('click', func_name);
If you're using jQuery 1.7+, though, you should either use .on():
$('#runtime').on('click', func_name);
or use a .click() handler directly:
$('#runtime').click(func_name);
try this
$(document).ready(function(){
$('.rem').click(function(){
$('<a id="runtime" href="javascript:void(0);">runtime</a>').bind('click',func_name).appendTo("body");
});
});//End of doc
function func_name(){
alert('I got it!');
}
Since you are binding the object before it has been created, you are not getting the desired result.
//-------------------------------------------------------
// event bind
// ex) $U.eventbind(window,"onresize",chart_common.draw);
//-------------------------------------------------------
, eventbind :
function (vobj, vEvent, pFunction, vrecheck) {
let obj = vobj;
if (typeof(vobj) === "string"){
obj = $hD(vobj);
}
let vFunction = pFunction.bind();
let vkey = pFunction.toString().replaceAll(/ /g,"");
$GC._U_EVENT_CAPTION.push(vkey)
$GC._U_EVENT_OBJ.push(vFunction);
if ($U.isNull(obj)){
if (vrecheck === true){
} else{
setTimeout(function(){ //--** 화면로드등으로 인해 시간이 지체되는 경우 3초뒤 한번더 체크
$U.eventbind(vobj, vEvent, vFunction, true);
},3000);
}
return;
}
if (obj === window){
obj.addEventListener(vEvent.substring(2), vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
return;
}
if ($U.isNullOrEmpty(vFunction)) return;
if ($U.isNull(obj.length) || obj.length === 0){
if (obj.addEventListener){
obj.addEventListener(vEvent.substring(2), vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
} else {
if (obj[vEvent]){
obj.attachEvent(vEvent, vFunction);
} else {
obj[vEvent] = vFunction;
}
}
} else {
for (var q=0,eoobj;eoobj=obj[q];q+=1){
if (eoobj.addEventListener){
eoobj.addEventListener(vEvent.substring(2), vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
} else {
if (eoobj[vEvent]){
eoobj.attachEvent(vEvent, vFunction);
} else {
eoobj[vEvent] = vFunction;
}
}
}
}
}
//-------------------------------------------------------
// event unbind
// addEvent 시 리턴받은 토큰이나 function Name 로 사용시
//-------------------------------------------------------
, eventunbind :
function (vobj, vEvent, pFunction, vrecheck) {
let obj = vobj;
if (typeof(vobj) === "string"){
obj = $hD(vobj);
}
let vFunction = pFunction;
let vkey = pFunction.toString().replaceAll(/ /g,"");
for(let iuyt=0,chkey; chkey=$GC._U_EVENT_CAPTION[iuyt]; iuyt+=1 ){
if (chkey === vkey){
vFunction = $GC._U_EVENT_OBJ[iuyt];
}
}
if ($U.isNull(obj)){
if (vrecheck === true){
} else{
setTimeout(function(){ //--** 화면로드등으로 인해 시간이 지체되는 경우 3초뒤 한번더 체크
$U.eventunbind(vobj, vEvent, vFunction, true);
},3000);
}
return;
}
if (obj === window){
obj.removeEventListener(vEvent.substring(2),vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
return;
}
if ($U.isNull(obj.length) || obj.length === 0){
if (obj.removeEventListener){
obj.removeEventListener(vEvent.substring(2),vFunction, {capture:false,once:false,passive:$GC._BROWSER_MOBILE_CHK} );
} else {
if (obj[vEvent]){
obj[vEvent] = null;
} else {
try{
obj.detachEvent(vEvent, vFunction);
} catch(e){
}
}
}
} else {
for (var q=0,eoobj;eoobj=obj[q];q+=1){
if (eoobj.removeEventListener){
eoobj.removeEventListener(vEvent.substring(2),vFunction, false );
} else {
if (eoobj[vEvent]){
eoobj[vEvent] = null;
} else {
try{
eoobj.detachEvent(vEvent, vFunction);
} catch(e){
}
}
}
}
}
}

JS Div tag is not hiding with if and else statements

function nes(){
if (document.getElementById('nes').style.display == 'block'){
document.getElementById('nes').style.display = 'none';
}
else if (document.getElementById('snes').style.display == 'block') {
document.getElementById('snes').style.display = 'none';
}
else if (document.getElementById('gba').style.display == 'block') {
document.getElementById('gba').style.display = 'none';
}
else if (document.getElementById('sega').style.display == 'block') {
document.getElementById('sega').style.display = 'none';
}
else if (document.getElementById('flash').style.display == 'block') {
document.getElementById('flash').style.display = 'none';
}
else if (document.getElementById('n64').style.display == 'block') {
document.getElementById('n64').style.display = 'none';
}
else if (document.getElementById('all').style.display == 'block') {
document.getElementById('all').style.display = 'none';
}
document.getElementById('snes').style.display = 'block';
}
<input id=nesdot type="image" src="C:\Users\Me\Documents\Website\Assets\Home Page\selection dot.png", onclick='nes()'/>
<div id=nes>
<input type="image" src="C:\Users\Sam Scolari\Documents\Totally Not An Arcade\Assets\Home Page\Adjusted Logos\NES.png"/>
</div>
<div id=all>
<input type="image" src="C:\Users\Sam Scolari\Documents\Totally Not An Arcade\Assets\Home Page\Adjusted Logos\A2Z.png"/>
</div>
I am trying to replace a picture that is in a div tag with javascript. When I click the button it seems to skip over all of the if and else statements and goes right to the single command at the end of the function. Is there something wrong with the syntax of the statements? It outputs to my website by adding the next image directly under the one that was supposed to be replaced. Any ideas? Thanks.
You might try this code:
function nes(){
var elem = document.getElementById('nes');
var displayStyleNes = null;
if (elem.style.display) {
displayStyleNes = elem.style.display;
} else if (elem.currentStyle) {
displayStyleNes = elem.currentStyle.display;
} else if (window.getComputedStyle) {
displayStyleNes = window.getComputedStyle(elem, null).getPropertyValue("display");
if (displayStyleNes === 'block'){
document.getElementById('nes').style.display = 'none';
}
//.....
}
Your IDs in HTML need quotes to be effective. The inspector won't prompt you any errors but the IDs will not be affected.
<input id="snes"/>
I assume that your function is wrapped in a script normally? If not, that is another problem!
Hope this helps :)

Show/Hide div with checkboxes using classes multiple times on a page

I am having trouble getting my script to work here. I am trying to target the show me span when the checkboxes are checked and it's not working.
Here is the code and link to fiddle: http://jsfiddle.net/dalond/nonyg6sm/
$('.single').live('change', ':checkbox', function() {
var target = $(this).closest('.single').prev().find('.showMe');
if ($(this).find('input:checked').length == 0) {
target.hide();
} else {
target.show();
}
});
I got it worked : http://jsfiddle.net/nonyg6sm/3/
$('input[type=checkbox]').click(function() {
var target = $(this).closest('.NoEd').prevAll(".Subs:first").find(".showMe");
if (this.checked) {
target.show();
} else {
target.hide();
}
});
You can modify it to feet your need.
UPDATE
http://jsfiddle.net/nonyg6sm/4/
$('input[type=checkbox]').click(function() {
var target = $(this).closest('.NoEd').prevAll(".Subs:first").find(".showMe");
if ($(this).closest('.NoEd').find("input[type=checkbox]:checked").length == 0) {
target.hide();
} else {
target.show();
}
});

form elements fade out with jQuery on selected option

I have this JavaScript code to fade out elements when a certain option is selected in the form, here is my code:
<script type="text/javascript">
function opt_onchange() {
if (document.getElementById("opt").value == "banscan") {
document.getElementById("form_username").style.visibility = "hidden";
document.getElementById("form_password").style.visibility = "hidden";
} else {
document.getElementById("form_username").style.visibility = "visible";
document.getElementById("form_password").style.visibility = "visible";
}
if (document.getElementById("opt").value == "") {
document.getElementById("submit").style.visibility = "hidden";
} else {
document.getElementById("submit").style.visibility = "visible";
}
}
</script>
When the option banscan is selected, the top 2 fields username and password fade out. But in Javascript they fade out instantly.
As I'm using bootstrap 3 on the website I thought I should try out jQuery as it is already available. I've read through some jQuery tutorials but I can't find anything specific to what I need. Here is my attempt:
<script type="text/javascript">
function opt_onchange() {
if (document.getElementById("opt").value == "") {
document.getElementById("submit").style.visibility = "hidden";
} else {
document.getElementById("submit").style.visibility = "visible";
}
if (document.getElementById("opt").value == "banscan") {
$("form_username").fadeOut();
$("form_password").fadeOut();
} else {
$("form_username").fadeIn();
$("form_password").fadeIn();
}
}
</script>
However, this code doesn't work at all.
Edit:
Here is my updated code, now I just need to make the submit button fade out on page load.
<script type="text/javascript">
$(document).ready(function() {
$("#submit").fadeOut();
});
function opt_onchange() {
if (document.getElementById("opt").value == "") {
$("#submit").fadeOut();
} else {
$("#submit").fadeIn();
}
if (document.getElementById("opt").value == "banscan") {
$("#form_username").fadeOut();
$("#form_password").fadeOut();
} else {
$("#form_username").fadeIn();
$("#form_password").fadeIn();
}
}
</script>
As #user3237539 pointed out, your jQuery selectors must begin with '#'. Your code should look like this:
<script type="text/javascript">
function opt_onchange() {
if (document.getElementById("opt").value == "") {
document.getElementById("submit").style.visibility = "hidden";
} else {
document.getElementById("submit").style.visibility = "visible";
}
if (document.getElementById("opt").value == "banscan") {
$("#form_username").fadeOut();
$("#form_password").fadeOut();
} else {
$("#form_username").fadeIn();
$("#form_password").fadeIn();
}
}
</script>
Hope that helps!
PS: Whenever you use document.getElementById() you could instead use $("#id") to be able to use more of jQuery's helpful functions. You could replace document.getElementById("submit").style.visibility = "hidden";
with $("#submit).hide();

Categories

Resources