I want a conditional redirection Javascript code - javascript

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.

Related

Javascript/Jquery Boolean help: Hiding/Showing Divs

Can someone explain to me what i am doing wrong in this code?
http://jsfiddle.net/14njfqef/
var isLoggedIn = function(state){
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else(state == false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
onload=function() {
isLoggedIn(false);
}
On load i want the divs to hide but then when i click the button i want the divs to show?
Is the boolean function set out in the correct way?
Piece below tries to re-arrange piece at OP. onload not appear clearly defined , not addressed , though could be attached to an event , i.e.g., window.onload = onload . Wrapped blocks in jquery .ready() event . Removed js onclick markup from html , included at script element , or loaded from file at jquery .on("click") event . Added strict comparison operator === (an added =) to if / else if statements. Changed input type to button. Added if to else portion of composition (see link posted at comments by Felix Kling).
Try
$(function() {
var isLoggedIn = function(state){
if(state === true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else if(state === false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
};
isLoggedIn(false);
$("input[type=button]").click(function() {
isLoggedIn(true)
})
});
jsfiddle http://jsfiddle.net/guest271314/14njfqef/3/
changed your html to
<input type="submit" value="Boolean" id="toggle"/>
rewrote your js as
// JQuery run at start effectivly
$(document).ready(function() {
function isLoggedIn(state) {
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else {
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
// JQuery attaching a click event using an anonymous function
// and hard coding your isLoggedIn to true, passing variables is a bit more complicated.
$('#toggle').click(function() {isLoggedIn(true)});
isLoggedIn(false);
})
Well there's a few things I am not sure if you are aware of so I feel there's some responsibility on my end to make sure they are mentioned. They are a number of syntactical errors in your post that are stopping this from working so instead of addressing them I feel its necessary to update your view on what JQuery you are using as well as your selector choice.
First I would add a class structure to all of the div's to target them all at once so you can save on some lines of code. In production it's always better to have less code for all of your visitors to download because even a little bit of code can get out of control after enough hits on a webpage. Having to serve it kills speed and so does having to process three separate jquery selections as opposed to one.
I would change the HTML to...
<body>
<div id='content-container' class='boxes'>
Content Container
</div>
<div id='account' class='boxes'>
account
</div>
<div id='account2' class='boxes'>
account2
</div>
<input id="validateButton" type="submit" value="Boolean">
</body>
This way you can simply target all divs with $(".boxes"); ... I wouldn't recommend getting into the habbit of using $("div");
Next I would change the JQuery to being more JQuery friendly code. Its not always useful to use an onload event from pure Javascript to handle JQuery driven functions in correct time to the loading of DOM objects. Therefore you should use $( document ).ready( handler ) to handle this load event properly just in case it causes you problems down the road. The more common shorthand of this ready event is a simple $(function() { }); wrapper.
The rest of the code can be re-arranged to this....
var isLoggedIn = false; //<--Instantiate to false, make global to window level scope
//Load event Corrected For JQuery
$(function() {
$(".boxes").hide(); //<--Hide on load
//Add A Proper Updated Click Event To Button
$("#validateButton").click(function() {
isLoggedIn = true; //<--Should include real functionality not hand coded to true
checkLoginAndRespond(); //<--Validate Login Status
});
});
function checkLoginAndRespond() {
//If Logged, Show
if(isLoggedIn) {
$(".boxes").show();
//Else Don't
} else { $(".boxes").hide(); }
} //end function
Lastly, the version. New versions of JQuery have not been released for some time and seem to not be in the making so its a safe bet to use their most recent versions as it has thousands of pages of help for its syntax and it's very stable. I would recommend anything in the 2.0 or higher series JQuery.
I am assuming you have JQuery library loaded. Try
if (state) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else{
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
to solve your problem.

document.getElementById() alternative in jQuery

UPDATE: I'm sorry that my thread was misinterpreted by many users. I'll try to be more clear.
I'm using Drupal and I have created three floating banners. On the frontpage there is a block (block1) that displays one floating banner and after refresh the second one is appearing and for the third too.
Like a wrote before these banners has a little X button to stop overflow.
I've putted this script in a one of the banners and it's working great.
<script language="javascript">
function doexpand() {
document.getElementById("block1").style.overflow = "visible";
}
function dolittle() {
document.getElementById("block1").style.overflow = "hidden";
}
</script>
The real problem is that in categories pages I have #block2 and in articles #block3.
These block are displaying the same banners. The code over is working only for a one ID. In this case #block1. document.getElementById is not working for more ID's as I read from other topics.
I've tried with jQuery with two blocks idents like this:
(function ($) {
function doexpand() {
$("#block1,#block2").css("overflow","visible");
}
function dolittle() {
$("#block1,#block2").css("overflow","hidden");
}
})(jQuery);
It's not working.
The firebug/console displays: ReferenceError: doexpand is not defined.
I've tried with a single block too with jQuery like this:
(function ($) {
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
})(jQuery);
and it's displaying the same error.
Note: Drupal has a different wrapping and it's like this:
(function ($) {
//your existing code
})(jQuery);
Please have a look on jQuery Selectors.
I think in your case, it is better to apply style with help of css for multiple elements. e.g. :
<script language="javascript">
function doexpand() {
$('.block').style.overflow="visible";
}
function dolittle() {
$('.block').style.overflow="hidden" ;
}
</script>
Please add class="block" to all of blocks for which you want to apply this style/function, it will apply on all of the blocks having css class "block".
jQuery?
HTML:
<div class="block2"></div>
JS:
function doExpand(selector) {
if ( $(selector).length ) {
$(selector).css({'overflow':'visible'});
}
}
Calling with non ID selector would look like this: (jQuery syntax):
doExpand('.block2');
The above code is perfectly valid in jQuery (which is a JavaScript library).
If you want to use a more typical jQuery code, you can do
$('#block1').css('overflow', 'visible');
You can expend it to multiple id like this :
$('#block1, #block2').css('overflow', 'visible');
You always can get the DOM object from a jQuery object, which means you could also have adapted your code to use jQuery selectors using
$('#block1').get(0).style.overflow="visible";
(this specific example isn't smart : no need to use jQuery if you don't use a complex selector or jQuery functions)
Pretty simple really, jQuery selection is based on css selectors for the most part. These selectors are then translated into an array of dom objects held in a jQuery object.
function doexpand() {
$("#block1").css("overflow","visible");
}
function dolittle() {
$("#block1").css("overflow","hidden");
}
You should never have more than one HTML element with the same ID (Which is why document.getElementById only returns one element)
You can just refeerence block2, block3 directly document.getElementById("block2").style.overflow="hidden" ;
Or use getElementByClassName
var elements = document.getElementsByClassName("yourClass")
Which will pick up all elements with a specific class.
If you want to use jQuery like the other answers are suggesting you can match on the element name. For example:
$('div[id^="block"]').css("overflow", "visible");
This will match all div element where their ID starts with block. You can also use other wildcards such as * for contains and $ for ends with.
Here is your Javascript Code in jQuery. I dont understand what you want do do, but you could pass the params in the function. Example under this code.
<script language="javascript">
function doexpand() {
$("#block1").css({'overflow': 'visible'});
}
function dolittle() {
$("#block1").css({'overflow': 'hidden'});
}
</script>
Here is it
<script language="javascript">
function doexpand(element) {
$("#" + element).css({'overflow': 'visible'});
}
function dolittle(element) {
$("#" + element).css({'overflow': 'hidden'});
}
</script>
Than you could call it like: doexpand("theIDofTheElement");
Alternative to document.getElementById("an_element);
in Jquery is: $("#an_element");
It will work fine in JQuery, it's just that JQuery makes things faster and less verbose.

Unhiding search result div with javascript or jquery without button click

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.

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