Unhiding search result div with javascript or jquery without button click - javascript

I'm very frustrated right now... and making lots of mistakes. Sorry about that
I've been trying to unhide a specific div based on search results
If no search was made the div should not appear, and this is easy with css, but once the search is done I have to change the style to 'block'.
Since I'm using the google custom search javascript its too hard to replace the button for another similar button that triggers my javascript function.
I also couldn't figure out how to replace the "resultDiv" into some more complex path
I already done this javascript function to hide a div based on the result div...
css div style is at #main.section .widget.HTML
function check()
{
if (document.getElementById('resultDiv')) {
if ($('.gsc-expansionArea').is(":empty")) {
document.getElementById('resultDiv').style.display = 'none';
}
else {
document.getElementById('resultDiv').style.display = 'block';
}
}
}
I think there might be 2 possible solutions. First is to load the script
<body onLoad="check();">
but doesn't seems to work.
Second would be check URL for ?q= meaning a search was done, but I don't know how to get these parameters from URL.
Please assist me. Thank you

well, since you've tagged jquery:
$(window).load(function(){
check();
})
and your function check() could be more like
function check() {
if ($('#resultDiv').length) {
if ($('.gsc-expansionArea').is(":empty")) {
$('#resultDiv').css({'display': 'none'})
}
else {
$('#resultDiv').css({'display': 'block'})
}
}
}
--
Second would be check URL for ?q= meaning a search was done, but I
don't know how to get these parameters from URL.
use location.search
Location search Property
MDN window.location

Replace
<body onLoad="javascript:check();">
with
<body onLoad="check();">

You can use
$(document).ready(function()
{
check();
}
to load the function when the page loads. You can also simplify your function with jQuery:
function check()
{
var isEmpty= $('.gsc-expansionArea').is(":empty");
$('#resultDiv').toggle(isEmpty);
}
The documentation for toggle is here.

Related

JS class change script? (Working in JS Fiddle)

JS noob here looking for some help. I've written something extremely basic in able to change a class which would hide a page element. The hide class just has a display none.
I've got it working fine in JS fiddle but when replicating it on my site, nothing happens? What am I doing wrong?
JS Fiddle - https://jsfiddle.net/MattPremier/x8rmn4cb/2/
<script type="text/javascript">
window.onload = function () {
var bookShow = "No";
if (bookShow == "No") {
// execute this code
document.getElementById('booking-show').classList.add('hide-widget');
}
else {
// execute this code
document.getElementById('booking-show').classList.add('show-widget');
}
};
</script>
<div id="booking-show" class="show-widget"><p>WORKING?</p></div>
I would recommend checking your CSS to make sure that the display isn’t otherwise set unless you need it to be set then inside the hide-widget CSS class put:
“display: none !important;”
And also remove show-widget from the object at the bottom as it might be conflicting with CSS.
Note Sorry for the bad formatting of this message as I’m on my cell phone.

I want a conditional redirection Javascript code

I'm looking for a small javascript code which will check for a div class and if it's not there then it will redirect the page to a site which is specified in javascript code.
I have this code, but I want it in document.getElementById form because I'm learning and I tried making the code. The below code is jQuery which I found here on this site.
function check() {
if ($('#demodivclass').length === 0) {
redirect(somesite.com);
}
Can anyone help?
To check if a class exists on an element you can use classList.contains(). Then you can redirect with location.assign(), like this:
function check() {
if (!document.getElementById('demodivclass').classList.contains('foo')) {
window.location.assign('http://somesite.com');
}
}
Try this code in order to check either a div has a specific classname and redirect after condition meets by using JQuery.
JQuery
if($( "#yourdivId" ).hasClass( "classname" ))
{
window.location.replace("https://stackoverflow.com");
}
Javascript
if(document.getElementById('yourdivId').className == 'classname')
{
window.location.replace("https://stackoverflow.com");
}
Hope it helps!
First of all to select your DOM element, you need to use getElementById with your ID that you defined previously. Then, to check if there is a class settled, you need to use classList.contains() method. Finally, to make a URL redirection, use window.location.href = 'Your link'.
function check() {
if (document.getElementById('element').classList.contains('class')) {
window.location.href = 'newPage.html';
}
}
Good luck and keep learning.
What the jQuery part of your code is doing is looking for elements with the id demodivclass using the ID selector. Using the document.getElementById() function as shown below will achieve the same thing.
If you want to check if a div that has a specific class exists (based on your question) the document.querySelector() function can be used instead.
To redirect the page use either location.replace or location.assign. Differences are highlighted at Difference between window.location.assign() and window.location.replace()
Redirect if ID does not exist:
function check() {
if (!document.getElementById('demodivclass')) {
window.location.replace("somesite.com");
// or
window.location.assign("somesite.com");
}
}
Redirect if class does not exist:
function check() {
if (!document.querySelector(".demodivclass")) {
window.location.replace("somesite.com");
// or
window.location.assign("somesite.com");
}
}
if($( "#div" ).hasClass( "divClass" )) /// check Is Exists or not
location.assign("https://stackoverflow.com");
else
alert('class not exist!')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="div" class="divClass"></div>
try this one. I hope it helps you.
function check() {
if ($('#demodivclass').length < 1) {
window.location.href = 'somesite.com';
}
Please try the following code, it is similar to your code. I just changed a little code of checking statement.

Show/Hide div using if then statement (javascript)

I have this show/hide set up here: http://jsfiddle.net/TwDSx/38/
What I would like to do is have the plus sign go away if the content is showing and vise versa if the content isn't showing hide the minus sign and show the plus.
I read articles on this using images to swap out, but nothing with just using html/css. Also, I would like to keep the javascript out of the html if this is possible, and just call for it externally.
any help is appreciated!
EDIT :
You can attach an event handler on your click to toggle the display attribute of the + or - button
$('#hide,#show').click(function(){
$('#hide,#show').toggle();
})
Quick demo:
http://jsfiddle.net/TwDSx/39/
I modified your Javascript a little and extended it so you can keep it in an external file, you just need to ensure you hide the #show div with CSS if you load the page with the content already showing, or vice-versa for the #hide.
The Javascript is as follows:
$('#show').click(function() {
ShowClick();
});
$('#hide').click(function() {
HideClick();
});
//This Javascript can be external
function ShowClick() {
$('#content').toggle('slow');
$('#hide, #show').toggle();
};
function HideClick() {
$('#content').toggle('fast');
$('#show, #hide').toggle();
};
The Js-Fiddle can be seen here: http://jsfiddle.net/mtAeg/
I think the simplest solution is to have only one button, #toggle, and to change the content of that button like so:
$('#toggle').click(function () {
if (this.innerHTML == '-') {
$('#content').slideUp('fast');
this.innerHTML = '+';
} else {
$('#content').slideDown('slow');
this.innerHTML = '-';
}
});
fiddle

Hide/show a icon depending upon the location.search?

Let us say i have a page http://www.abc.com/xyz.html and i am going to access this page in two ways
simple as it is
I will append some stuff to the url e.g. http://www.abc.com/xyz.html?nohome by just putting the value ?nohome manually in the code.
Now i will add some javascript code something like this
$(document).ready(function () {
if (location.search=="?value=nohome") {
// wanna hide a button in this current page
}
else {
// just show the original page.
}
});
Any help will be appreciated.
As you are using jQuery to catch the DOM-ready event, I guess a jQuery solution to your problem would be fine, even though the question isn't tagged jQuery:
You can use .hide() to hide and element:
$(document).ready(function () {
if (location.search=="?value=nohome")
{
$("#idOfElementToHide").hide();
}
// Got rid of the else statement, since you didn't want to do anything on else
});

JavaScript Dynamic onClick problem

I am trying to give a button an onclick event when a certain thing on a page changes. I have tried to do it many different ways and none have worked. What am I doing wrong?
Below are what I have tried.
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');";
function redErrorAlert()
{
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redErrorAlert;
document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false);
document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false);
Note: subDiv is a variable containing the id of the element.
You need to wait for the DOM tree to be created before you do queries on it.
Make sure that this all happens within a context that is created after the DOM tree has been built:
window.onload = function() {
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
};
document.getElementById() takes a string containing the ID of the element you're trying to find. Assuming you're looking for the element with id 'subDiv', you should be calling document.getElementById('subDiv').
(It's also possible that the variable subDiv in your code is a string containing the ID, but since you didn't mention it I'm assuming that it doesn't.)
EDIT: If you were to go with virstulte's suggestion of using jQuery, you'd attach a function to the document.ready event in order to ensure that the DOM has been built by the time your code runs. Example:
$(document).ready(function() {
$("#subDiv").click(function() { alert("Test!"); });
});
This sounds like jQuery territory here. Once you learn the ins and outs of jQuery, things like this are a snap to take care of, and you'll find yourself writing a lot less JavaScript.
First, get jQuery from http://jquery.com/
Then put this in your code to bind the event:
$('#idOfElementToBindClickEvent').click(function(){
alert('Error.');
});
jQuery basically provides a way to manipulate elements using CSS-like selectors.
try
document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page');
or
function redAlert() {
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redAlert();
First case: you need to call the function, and you've assigned a string
Second case: you've assigned a function and you were not calling this function

Categories

Resources