Javascript onclick function - 2 clicks needed to work - javascript

I have the following Javascript code:
function toggleSearch() {
if(document.getElementById("searchitem").style.display == "block" ) {
document.getElementById("searchitem").style.display = "none";
document.getElementById("topsearchform").style.display = "block";
}
else {
document.getElementById("searchitem").style.display = "block";
}
}
function backtonormal() {
if(document.getElementById("searchitem").style.display == "none" ) {
document.getElementById("searchitem").style.display = "block";
document.getElementById("topsearchform").style.display = "none";
}
else {
document.getElementById("searchitem").style.display = "none";
}
}
And the following HTML Code:
<li id="searchitem">
<span>Search<span class="cursor"></span></span></li>
<li>
<div id="topsearchform">
<form class="topsearchform" action="http://www.ovisionmedia.com/search/" method="get" target="_top">
<input type="text" name="search_text" class="search_text" onblur="backtonormal();" autofocus/>
<input type="button" name="button" class="button">
</a>
</form>
</div>
</li>
The code is for a custom wordpress menu item which I created as follows:
function wpa_58902($items, $args){
if( 'main-menu' === $args -> theme_location ) {
$search = '<li id="searchitem"><span>Search<span class="cursor"></span></span></li>';
$search .= '<li><div id="topsearchform"><form class="topsearchform" action="http://www.ovisionmedia.com/search/" method="get" target="_top">';
$search .= '<input type="text" name="search_text" class="search_text" onblur="backtonormal();" autofocus/><input type="button" name="button" class="button"></a></form></div></li>';
}
return $items . $search;
}
add_filter('wp_nav_menu_items','wpa_58902',10,2);
The Javascript function should be executed when the searchitem link is clicked ( 1 time).
Problem: I have to click 2 times so the function will be executed.
2nd Problem:
What code do I have to add to the Javascript function for the form input to be automatically focused? Right now the auto focus is only working if I reload the page.
Thank you very much!!
EDIT:
PROBLEMS SOLVED
#Zlatan O. - thank you very much! I found a solution on my own :-)
The Problem was that on the first click display:block was not set.
After the first click display:block has been set and so on the second click it worked.
Here is the working code without using jquery:
function toggleSearch() {
document.getElementById("searchitem").style.display = "block";
if(document.getElementById("searchitem").style.display == "block" ) {
document.getElementById("searchitem").style.display = "none";
document.getElementById("topsearchform").style.display = "block";
document.getElementById('search_text2').focus();
}
else {
document.getElementById("searchitem").style.display = "block";
}
}
function backtonormal() {
if(document.getElementById("searchitem").style.display == "none" ) {
document.getElementById("searchitem").style.display = "block";
document.getElementById("topsearchform").style.display = "none";
document.getElementById('search_text2').focus();
}
else {
document.getElementById("searchitem").style.display = "none";
}
}
maybe it is not the best solution - I don't know - but it works :-)
Again thank you very much!!

In jQuery you can do it like this:
$(document).ready(function() {
$('li#searchitem a').click(function() {
$('#searchitem, #topsearchform').toggle();
$('input[name="search_text"]').focus();
});
$('input[name="search_text"]').blur(function() {
$('#searchitem, #topsearchform').toggle();
});
});
Done!

Related

How to use multiple (dynamic) toggle buttons with same ID on the same page?

I have a dynamic output from database in my PHP code.
In the code, I have a toggle button which is added to every output element.
The problem is, toggle is properly working only for the first element.
All other elements are just messed up: everything is visible by default and when clicking a button it just scrolls to the first element.
PHP/HTML:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div class='details'>
<h4>".$row['image_text']."</h4>
<input type='submit' id='title_btn' onclick='changeTitle(this)' value='Edit title'>";
echo "<form action='edittitle.php' method='POST' id='newtitle' autocomplete='off'>
<input type='text' name='newtitle' value='".$row['image_text']."'/>
<input type='submit' name='edit' id='title_btn2' value='Save title'>
</form>";
</div>";
}
?>
JavaScript:
window.onload = function() {
document.getElementById('newtitle').style.display='none';
document.getElementById('title_btn2').style.display='none';
}
function changeTitle(eref) {
var x = document.getElementById('newtitle');
eref.style.display = 'none';
var btn;
if (eref.id == 'title_btn') {
btn = document.getElementById('title_btn2');
x.style.display = 'inline-block'
} else {
btn = document.getElementById('title_btn');
x.style.display = 'none';
}
btn.style.display = 'inline-block';
}
I would prefer pure JavaScript solution but if that is not possible, I wouldn't mind using jQuery aswell.
Any help is appreciated!
As #misorude said ID's have to be unique, so go with a class name instead.
JSFiddle example
var editToggler = document.querySelectorAll('.title_btn');
var forms = document.querySelectorAll('.newtitle');
var savebtn = document.querySelectorAll('.title_btn2');
editToggler.forEach(function(btn) {
btn.addEventListener('click', function() {
btn.parentElement.querySelector('.newtitle').style.display = 'block';
btn.style.display = 'none';
});
});
forms.forEach(function(f) {
f.addEventListener('submit', function(e) {
e.preventDefault();
});
});
savebtn.forEach(function(btn) {
btn.addEventListener('click', function() {
btn.parentElement.style.display = 'none';
btn.parentElement.parentElement
.querySelector('.title_btn')
.style.display = 'block';
});
});
Use jQuery .each():
$('.ClassName').each(function(){
// get current element
var it = $(this);
// hide, show ...
it.hide();
it.show();
// show element -> parent -> children with class .benny
it.parent().children('.benny').show();
});

Change website background with JavaScript not working

Okay, I want to change my website background with JavaScript. Ideally with a drop down menu, but for now, buttons.
This works:
function selText(test){
var arr = document.getElementById(test).value;
if (arr == 1){
document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
}
else if (document.getElementById('btnim2')){
document.body.style.background = 'none';
}
}
<button id="btnim" value="1" onclick="selText(this.id)">text</button>
<button id="btnim2" value="2" onclick="selText(this.id)">more text</button>
However, if I set my 'else if' to arr == 2 and both buttons have the same id (btnim) it doesn't work, and I don't know why. I feel like I am missing something simple. What am I doing wrong?
if you use arr==2 and id remains btnim2 of button 2 it will still work. You can't have same id's of many elements in webpage because it will confuse the javascript compiler to target which element.
function selText(test){
var arr = document.getElementById(test).value;
if (arr == 1){
document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
}
else if (arr==2){
document.body.style.background = 'none';
}
}
<button id="btnim" value="1" onclick="selText(this.id)">text</button>
<button id="btnim2" value="2" onclick="selText(this.id)">more text</button>
There is another way to make this code work by passing the value of the button instead of id.
function selText(test){
var arr = test;
if (arr == 1){
document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
}
else if (arr==2){
document.body.style.background = 'none';
}
}
<button id="btnim" value="1" onclick="selText(this.value)">text</button>
<button id="btnim2" value="2" onclick="selText(this.value)">more text</button>
Send the button itself as parameter instead:
<script type="text/javascript">
function selText(button){
var arr = button.value;
if (arr == 1){
document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
} else if (arr == 2) {
document.body.style.background = 'none';
}
}
</script>
<button id="btnim" value="1" onclick="selText(this)">text</button>
<button id="btnim2" value="2" onclick="selText(this)">more text</button>

How to make javascript toggle button?

I have this code but it doesn't work:
HTML:
<button id="btn_search">Search</button>
<input id="srh" type="search">
JS:
var btnSearch = document.getElementById("btn_search");
var search = document.getElementById("srh");
if (document.addEventListener) {
btnSeach.addEventListener('click',activeSearch);
} else if (document.attackEvent) {
btnSearch.attackEvent('onclick',activeSearch);
}
function activeSearch (event) {
event.preventDefault();
if (search.style.width == '0') {
search.style.width = '14.8em';
search.style.opacity = '1';
} else if (search.style.width == '14.8em') {
search.style.width = '0';
search.style.opacity = '0';
}
I need a toggle button
What should I do?
I might think about using a CSS class and toggle() to show/hide you element.
var btnSearch = document.getElementById("btn_search");
btnSearch.addEventListener('click', function(event){
var search = document.getElementById("srh");
search.classList.toggle("hidden");
event.preventDefault();
});
#srh { width: 14.8em; }
#srh.hidden { display: none; }
<button id="btn_search">Search</button>
<input id="srh" type="search" />
You can simply use JQuery to simplify all the proccess. Make all the code as simple as:
function magictoggle(a) {
if (a == 1) {
$("#btn1").attr("onclick", "magictoggle(0)");
$("#searchbox").hide(1000);
//1000 Are the miliseconds will take the box to hide
} else {
$("#btn1").attr("onclick", "magictoggle(1)");
$("#searchbox").show(1000);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="magictoggle(1)">Search</button>
<input type="text" id="searchbox" placeholder="A search Box">

localstorage how to save a div

I need to save a div with localstorage. When i press a button the div becomes visible but when i close the browser and open it again the div needs to be visible.
This is my code so far:
<script>
function openDiv() {
var film = document.getElementById("bookingDiv");
if(film.style.display == "none"){
film.style.display = "block";
}
}
function save() {
openDiv()
var saveDiv = document.getElementById("bookingDiv")
if(saveDiv.style.display == "block"){
localstorage.setItem("text", saveDiv)
}
}
function load() {
var loadDiv = localstorage.getItem("text")
if(loadDiv){
document.getElementById("bookingDiv") = loadDiv
}
}
</script>
<body onload="load()">
<input type="button" id="testButton" value="Save" onclick="save()" />
<div style="display:none" id="bookingDiv" type="text">
hello
</div>
</body>
You can only store strings using the localStorage. So you have to store the state of this element instead of the element itself.
function save() {
openDiv();
var saveDiv = document.getElementById("bookingDiv");
if (saveDiv.style.display == "block") {
localStorage.setItem("isTextVisible", true);
}
}
function load() {
var isTextVisible = localStorage.getItem("isTextVisible");
if (isTextVisible == "true") {
openDiv();
}
}
note: do not forget the semicolon after each statement as it might lead to wrong behavior!

Javascript:Toggle Function is not working

I am trying to make a simple toggle but it is not working.And i want it done in javascript not in jquery.
Here is my javascript.
<script>
function showhide() {
if (document.getElementById(ptag).style.display = "block") {
document.getElementById(ptag).style.display = "none";
} else {
document.getElementById(ptag).style.display = "block";
}
}
</script>
Here is my HTML.
<input type="button" value="Show hide" onclick="showhide()">
<p id="ptag">Some text here.</p>
I need solution :(
Change your if condition to:
if(document.getElementById("ptag").style.display == "block"){
^^^^ string ^^^ double equals
And replace all other references of ptag to "ptag"
See working JSFiddle

Categories