Minor tweak to this javascript function? - javascript

I have a script that shows/hides used via onClick. I can get it to show/hide just fine, but I can't get it to show/'hide everything else'. So what I get is a bunch of open containers when I really want just the one.
Javascript:
<script>
function showfields(fields){
if(document.getElementById(fields).style.display=='none'){
document.getElementById(fields).style.display='block';
}
else{
document.getElementById(fields).style.display = 'none';
}
}
</script>
HTML:
<div id="hidden" class="steps" style="display: block;">
<div class="section" style="margin-right: 10px;">
<h2>Something</h2>
</div>
<button class="continue dropdown" id="showLink" onClick="showfields('hidden2');return false;" href="#">Continue</button>
</div>
<div id="hidden2" class="steps" style="display: block;">
<div class="section" style="margin-right: 10px;">
<h2>Something2</h2>
</div>
<button class="continue dropdown" id="showLink" onClick="showfields('hidden3');return false;" href="#">Continue</button>
</div>
<div id="hidden3" class="steps" style="display: block;">
<div class="section" style="margin-right: 10px;">
<h2>Something3</h2>
</div>
<button class="continue dropdown" id="showLink" onClick="showfields('hidden3');return false;" href="#">Continue</button>
</div>
<div id="hidden4" class="steps" style="display: block;">
<div class="section" style="margin-right: 10px;">
<h2>Something4</h2>
</div>
<button class="continue dropdown" id="showLink" onClick="showfields('hidden4');return false;" href="#">Continue</button>
</div>
Thanks

Since you've tagged this with jQuery I assume that is an option:
function showfields(fields){
$('.steps').hide()
$('#' + fields).show();
}

Edit:
Is this what you're trying to do: http://jsfiddle.net/Rykus0/67cjt/2/
(without jQuery)
(ps - this can be done better)
Your question is not very clear, but I'm guessing that you want the page to start with the everything but the first div hidden.
In that case, what you have is fine, just set style="display:none;" on the elements you don't want to show at first (you can also use a class).
Also, I believe you should change the onclick call on hidden3 to be showfields('hidden4') and remove the onclick event from hidden4

I agree with Porco,
Another option would be using a class as a flag, for example
function showFields(fields){
$(fields).each(function(){
if($(this).hasClass('visible'){
$(this).hide();
}
else {
$(this).show();
}
}
}

Without using jquery .This piece of javascript may help you
<script>
function showfields(fields){
for(var i=0;i<document.body.getElementsByTagName("*").length;i++)
{ if(document.body.getElementsByTagName("*")[i].id==field)
{
document.body.getElementsByTagName("*")[i].style.display='block';
}
else{
document.body.getElementsByTagName("*")[i].style.display='block';
}
}
</script>

Related

Find div before button

Im trying addClass to wizard-step when button clicked, but still no luck :/
<div class="mt-4">
<div class="wizard-steps">
<div class="wizard-step">
<div class="wizard-step-icon">
<i class="far fa-user"></i>
</div>
</div>
<form class="wizard-content mt-2" id="regForm">
<fieldset>
<div class="form-group row">
<div class="col-lg-4 col-md-6 text-right">
<button type="button" onclick="step0(this);" class="btn">Next</button>
</div>
</div>
</fieldset>
</form>
</div>
JavaScript:
<script>
function step0(element) {
$(element).prev('div').find('.wizard-step').addClass('wizard-step-active');
}
</script>
Can anyone please help me !
prev is used to retrieve a previous sibling element. The .wizard-step you want to target is a child of a sibling to a parent of the button being clicked. As such you need to use closest() instead.
Also note that onclick (and all the other onX attributes) are not good practice and should be avoided. As you're already using jQuery you can attach your event unobtrusively, like this:
jQuery($ => {
$('.btn').on('click', function() {
$(this).closest('.wizard-steps').find('.wizard-step').addClass('wizard-step-active');
});
});
.wizard-step-active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mt-4">
<div class="wizard-steps">
<div class="wizard-step">
<div class="wizard-step-icon">
<i class="far fa-user">User icon</i>
</div>
</div>
<form class="wizard-content mt-2" id="regForm">
<fieldset>
<div class="form-group row">
<div class="col-lg-4 col-md-6 text-right">
<button type="button" class="btn">Next</button>
</div>
</div>
</fieldset>
</form>
</div>
Alternatively, instead of calling find() from the shared parent, you could select the form and use prev():
$('.btn').on('click', function() {
$(this).closest('.wizard-content').prev('.wizard-step').addClass('wizard-step-active');
});
Either is fine, it just depends on how your HTML is structured as to which fits best for this use case.
You don't want the div immediately before the button, but the one containing the relevant item(s). So instead of $(element).prev('div') write $('.mt-4').
Your this parameter is referring your button, not your div.
You can do this without Jquery, just using your function like this:
function step0() {
const element = document.getElementsByClassName('wizard-step');
element.classList.add('wizard-step-active');
}
So, you don't need to pass this as a parameter to step0 function.

Selecting the first instance of a html class with jQuery

I'm having some trouble with jQuery overwriting the elements of a particular parent class. For instance, I have two classes that have the same name but I am looking only to use the first instance for a particular purpose and then the others for something else, but the data inside keeps being overwritten by the next function I am using. I think I know why it is doing it, I'm just unsure of how to fix it so it doesn't.
Here is my jQuery code:
function buildFriendStatus() {
$.getJSON('/members/feed/get-friend-status', function(data) {
var notFirstElement = $('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:not(first)')
$.each(data, function(i, item) {
var element = notFirstElement.eq(i);
element.find('h4').html(data[i].username);
element.find('p').html(data[i].status);
element.find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response.fail);
});
}
function buildSelfStatus() {
$.getJSON('/members/feed/list-own-status', function(data) {
$.each(data, function(i, item) {
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('h4').html(data[i].username);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('p').html(data[i].status);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin:first').find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response.fail);
});
}
setInterval(function() {
buildFriendStatus();
}, 1000);
and then the html/calling of the functions
<script type="text/javascript">
buildSelfStatus();
buildFriendStatus();
</script>
<!-- always have this first (sticky) for the user status -->
<div class="w3-container w3-card-2 w3-white w3-round w3-margin">
<h4></h4>
<p></p>
<div class="w3-row-padding" style="margin: 0 -16px;">
<div class="w3-half">
<img src="" style="width: 100%; height: 200px;" alt="<?php echo $this->identity() . "'s image"; ?>" class="w3-margin-bottom w3-round w3-border">
</div>
</div>
</div>
<div class="w3-container w3-card-2 w3-white w3-round w3-margin">
<h4></h4>
<p></p>
<div class="w3-row-padding" style="margin: 0 -16px">
<div class="w3-half">
<img src="" style="width: 100%; height: 200px;" alt="<?php echo "Image"; ?>" class="w3-margin-bottom w3-round w3-border">
</div>
</div>
<button type="button" class="w3-btn w3-theme-d1 w3-margin-bottom">
<i class="fa fa-thumbs-up"></i> Like
</button>
<button type="button" class="w3-btn w3-theme-d2 w3-margin-bottom">
<i class="fa fa-comment"></i> Comment
</button>
</div>
Here is a screenshot of the issue.
Updated screenshot (shows the first image but not the other result(s) now)
Any help would be appreciated
Thanks!
Oh, on another note, is there a way to use jQuery to put data inside the class but have the class be shown more than once without overwriting the data previously added but only have one <div> element with the class name? Sort of like the screenshot attached but just not overwriting each class the same time. Just curious as I couldn't find anything regarding this. I guess I mean build the div element and it's child elements dynamically based on the results retrieved via $.getJSON.
$(".getfirst").click(function(){
alert($(".testdiv").first().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testdiv">
33
</div>
<div class="testdiv">
44
</div>
<div class="testdiv">
55
</div>
<div class="testdiv">
66
</div>
<div class="getfirst" style="width:150px; height:50px; background-color:red;">
get me!!
</div>
Why dont you use .first() of jQuery?
For example lets say you have 4 divs with same class but you want to get the text of the first div element with the specific class name:
<div class="testdiv">33</div>
<div class="testdiv">44</div>
<div class="testdiv">55</div>
<div class="testdiv">66</div>
<div class="getfirst" style="width:150px; height:50px; background-color:red;">
get me!!
</div>
$(".getfirst").click(function(){
alert($(".testdiv").first().text());
});
just added another class to the first element.

Display html of previous element using jquery?

I am a beginner.
I want to display the HTML of previous element when the button is clicked.
I am able to display HTML content of button using outerHTML property. But when i use prev() function with the current object, it is showing error.
function show(currentObject) {
alert($(currentObject)[0].outerHTML);
}
above code gives the html content of the current button.
(Click) is shows as alert.
but
function show(currentObject) {
var prevObject = $(currentObject).prev();
alert($(prevObject)[0].outerHTML);
}
above code is giving me error!!
error: TypeError: $(...)[0] is undefined
Below is the html
<div class="row">
<div class="col-md-12"><a class="navbar-link" href="/somelink">linktext</a></div>
<div class="col-md-12"><p>click below button</p></div>
<div class="col-md-4"><button onclick="show(this)" class="btn btn-primary">Click</button></div>
</div>
Is there a way to do it right?
You can use .prev().html() to getting previous element html, check updated snippet below..
alert($('.currentItem').prev().html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">Previous Element</div>
<div class="item1 currentItem">Current Element</div>
If you want to use pure Javascript use previousElementSibling
document.getElementById('foo').addEventListener('click', currentObject);
function currentObject() {
alert(this.parentNode.previousElementSibling.outerHTML);
}
body {
font: 13px Verdana;
}
<div class="row">
<div class="col-md-12"><a class="navbar-link" href="/somelink">linktext</a></div>
<div class="col-md-12">
<p>click below button</p>
</div>
<div class="col-md-4"><button class="btn btn-primary" id="foo">Click</button></div>
</div>

jquery open div with dynamic id

I want to use jQuery to open and close a div.
But because the code that I use is dynamic and will be repeated below each other, I need to use a dynamic id.
HTML:
<div class="categoryratings-review-<?php echo $this->htmlEscape($_review->getId())?>" style="display: none;">
<p>Text</p>
</div>
<span class="showcategoryratings" id="review-<?php echo $this->htmlEscape($_review->getId())?>">
<span class="showcategoryratings-text">Per category</span>
</span>
I try to use this jQuery, but I guess the php line is not working:
$(document).ready(function() {
$('#review-<?php echo $this->htmlEscape($_review->getId())?>').click(function() {
$('.categoryratings-review-<?php echo $this->htmlEscape($_review->getId())?>').slideToggle("fast");
$(this).toggleClass('active');
});
});
How do I need to edit this correctly?
You can do it without PHP in your Javascript.
$(document).ready(function() {
$('.showcategoryratings').click(function() {
var categoryId = $(this).attr('id').split('-')[1];
$('.categoryratings-review-'+categoryId).slideToggle("fast");
$(this).toggleClass('active');
});
});
I think it works.
It'd be easier if you'd grouped your elements like below. By doing so, you don't need IDs at all. Take a look.
$(document).ready(function() {
$('.showcategoryratings').on("click", function() {
$(this).closest(".group").find(".categoryratings-review").slideToggle("fast");
$(this).toggleClass('active');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group">
<div class="categoryratings-review" style="display: none;">
<p>Text1</p>
</div>
<span class="showcategoryratings">
<span class="showcategoryratings-text">Per category1</span>
</span>
</div>
<div class="group">
<div class="categoryratings-review" style="display: none;">
<p>Text2</p>
</div>
<span class="showcategoryratings">
<span class="showcategoryratings-text">Per category2</span>
</span>
</div>
<div class="group">
<div class="categoryratings-review" style="display: none;">
<p>Text3</p>
</div>
<span class="showcategoryratings">
<span class="showcategoryratings-text">Per category3</span>
</span>
</div>
you can hook up all id's that start with review- to respond
$('[id^="review-"]').click(function() {
$( '.categoryratings-' + $(this).attr('id') ).slideToggle('fast') ;
$( this ).toggleClass('active');
});

Toggle between multiple divs

I have an issue. I want to toggle between many divs, while one shows the rest hide.
This is what I have so far.
Thanks in advance!
<a href="#n" onclick="toggle_visibility('box1');">
<div class="square img_1-1"></div>
</a>
<a href="#n" onclick="toggle_visibility('box2');">
<div class="square img_1-2"></div>
</a>
<a href="#n" onclick="toggle_visibility('box3');">
<div class="square img_1-3"></div>
</a>
<div id="box1" style='display:none;'>
<div class="trabajo">
<p>box1</p>
</div>
</div>
<div id="box2" style='display:none;'>
<div class="trabajo">
<p>box2</p>
</div>
</div>
<div id="box3" style='display:none;'>
<div class="trabajo">
<p>box3</p>
</div>
</div>
<a href="#n" onclick="toggle_visibility('box4');">
<div class="square img_2-1"></div>
</a>
<a href="#n" onclick="toggle_visibility('box5');">
<div class="square img_2-2"></div>
</a>
<a href="#n" onclick="toggle_visibility('box6');">
<div class="square img_2-3"></div>
</a>
<div id="box4" style='display:none;'>
<div class="trabajo">
<p>box4</p>
</div>
</div>
<div id="box5" style='display:none;'>
<div class="trabajo">
<p>box5</p>
</div>
</div>
<div id="box6" style='display:none;'>
<div class="trabajo">
<p>box6</p>
</div>
</div>
Also, here is the Javascript. I'm using toggle_visibility(id) The problem is that it start to get weird when I hide one box and open another it opens both then it just gets weird. It leaves both open then closes one.
var prevId;
function toggle_visibility(id) {
if(prevId && id !== prevId){
$("#"+prevId).toggle();
}
var e = document.getElementById(id);
$(e).toggle();
prevId = id;
}
There's also another javascript code I tried before, this one works sorta fine, the only thing it doesn't do is toggle it just shows the work and doesn't hide it, although it does toggle between different work.
top.visible_div_id = 'box1';
function toggle_visibility(id) {
var old_e = document.getElementById(top.visible_div_id);
var new_e = document.getElementById(id);
if(old_e) {
console.log('old', old_e, 'none');
old_e.style.display = 'none';
}
console.log('new', new_e, 'block');
new_e.style.display = 'block';
top.visible_div_id = id;
}
Instead of the onclick, I used the eventhandler on() (you should not inline-javascript). I coombine this with the data-attribute:
<a data-toggles="#box2">box 2</a>
And some changes to your javascript:
$('a.triggeringAnchor').on('click', function(e){
e.preventDefault() // stop the anchor
$('a.triggeringAnchor').hide(); // hide them all
$( $(this).data('toggles') ).show(); // bring the one back in the one back
})
You could use the :not() selectors, but this is a bit more obvious :)
The trick here is the 'bring back' line. I use the value of the data-attribute as selector for the actual element we want back.
This code has a big advantage over yours. If you add 1 more element, your counter would be to know about this (could be done via .length()), my code doesn't care. Everything gets hidden, and just that 1 will come back.
I think this jQuery Widget is exactly what you are looking for. Easy to implement and very usable. Plus, the jQuery API instructions make it a breeze to get onto your page.

Categories