alias51
alias51

Reputation: 8628

How to toggle prepend in jquery

I want to toggle a css link using a jquery, via a single button.

Catch is, I want to do it in the target of an iframe.

So far I have the following code, which insets the link fine:

$("#custom").click(function() {
    $("#content").contents().find("head").prepend("<link href=\"../build/css/custom.css\" rel=\"stylesheet\" id=\"custom-css\">");
});

This is activated by the following html:

<div class="toggle-custom">
<a target="custom" id="custom" class="btn btn-primary btn-lg">Toggle custom style</a>
</div>
<iframe id="content" src="carousel.html" frameborder="0" scrolling="auto">
</iframe>

I know that the way to remove it is:

$("#content").contents().find("#custom-css").remove();

But how can I toggle it from the same button?

Thanks

Upvotes: 1

Views: 1750

Answers (3)

alias51
alias51

Reputation: 8628

Here's the full syntax:

$("#custom").click(function() {
          var head = $("#content").contents().find("head");
    var ccss = head.find("#custom-css");
    if (ccss.length) {
        ccss.remove()
    } else {
        head.prepend("<link href=\"../build/css/custom.css\" rel=\"stylesheet\" id=\"custom-css\">");
    }
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388396

Try

var contents = $("#content").contents();
var ccss = contents.find("head").find("#custom-css");
if(ccss.length){
    ccss.remove()
} else {
    contents.find("head").prepend("<link href=\"../build/css/custom.css\" rel=\"stylesheet\" id=\"custom-css\">");
}

Upvotes: 1

James Robert Albert
James Robert Albert

Reputation: 424

Put the link in the html, then toggle it on click.

$(document).ready(function(){
    $('#custom-css').hide();
    $("#custom").click(function() {
        $('#custom-css').toggle();
    });
});

Upvotes: 0

Related Questions